我想将从服务器接收到的对象转换为JSON文件,以便可以在d3.js图表中使用它:
data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
输出应为:
{
"name" : "animal",
"children" : [
{"name":"dog", "value": 5},
{"name":"cat", "value": 4},
{"name":"fish", "value": 10}
]
}
我想到的是:
var jsonText = [] ;
for ( key in data) {
jsonText.push({name : key.trim(), value : parseInt(data[key])});
}
但是当我尝试打印出对象时,会收到:
[object Object],[object Object],[object Object]
除此之外,我不知道如何向JSON文件添加其他属性。因此,感谢您的提示。
答案 0 :(得分:2)
您可以使用Object.keys(data)
并遍历key
以获得所需的对象结构。
var data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
};
var res = {
name: "animal",
children: []
};
Object.keys(data).forEach((key)=>{
res.children.push(
{name:key.trim(), value: parseInt(data[key])}
);
});
console.log(res);
答案 1 :(得分:2)
假设您正在手动添加诸如animal
之类的键,这应该可以工作,并且值应该为整数。
var data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
var children = Object.keys(data).map((key) => {
return {
name: key.trim(),
value: parseInt(data[key])
}
})
let result = JSON.stringify({
name: 'animal',
children
})
console.log(result);
将会返回
{"name":"animal","children":[{"name":"dog ","value":5},{"name":"cat ","value":4},{"name":"fish ","value":12}]}
答案 2 :(得分:2)
您快到了(数组的格式正确),但是您需要将结果数组作为对象的children
属性的值。使用Object.entries
和map
也会更容易一些,它们基于相同的元素将一个数组转换为另一个数组:
const data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
};
const children = Object.entries(data)
.map(([name, value]) => ({ name: name.trim(), value: Number(value) }));
const output = { name: 'animal', children };
console.log(output);
答案 3 :(得分:1)
尝试-console.log(JSON.stringify(jsonText))
答案 4 :(得分:1)
使用children
键创建一个对象并将其推入值
let data = {
"dog ": "5",
"cat ": "4",
"fish ": "12",
}
let newObj = {
"name": "animal",
"children": []
}
for (let keys in data) {
newObj.children.push({
name: keys.trim(),
value: parseInt(data[keys], 10)
});
}
console.log(newObj)
答案 5 :(得分:1)
您可以使用var url = v.url;
if(!url.match(/^https:\/\//)){
return false;
}
遍历data
对象,并将for..in
对对象放入您的prop: value
数组中:
children
答案 6 :(得分:1)
您可以这样做
const data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
Object.keys(data).reduce((obj, animal) => ({
...obj,
children: [
...obj.children,
{
name: animal,
value: data[animal]
}
]
}), {name: "animal", children: []})
console.log(JSON.stringify(obj))
我认为这是一种获得预期结果的更干净的方法