我有以下JSON格式的数据集,我希望将其转换为d3.js中可以使用的内容:
{
"rank_type_1":{
"d1":0,
"d2":1,
"d3":2
},
"rank_type_2":{
"d1":1,
"d2":0,
"d3":2
},
"rank_type_3":{
"d1":2,
"d2":0,
"d3":1
}
}
根据d1,d2和d3的排名,我有3种等级。现在,我想将其转换为以下格式:
[
{
"id":d1
"rank_type_1" :0
"rank_type_2" :1
"rank_type_3" :2
},
{
"id":d2
"rank_type_1" :1
"rank_type_2" :0
"rank_type_3" :2
},
{
"id":d3
"rank_type_1" :2
"rank_type_2" :2
"rank_type_3" :1
}
]
原因是当我记录d3.csv函数的输出时,它具有类似的格式。也就是说,它是一个对象数组,第一个对象的键被转换为输出数组中的值。
我尝试过使用Object.entries,Object.keys,Object.values但没有成功。
答案 0 :(得分:1)
您可以使用Object.keys()
和forEach()
执行此操作以循环对象并添加到数组。
var data = {"rank_type_1":{"d1":0,"d2":1,"d3":2},"rank_type_2":{"d1":1,"d2":0,"d3":2},"rank_type_3":{"d1":2,"d2":0,"d3":1}}
var result = [];
Object.keys(data).forEach(function(e) {
var that = this;
Object.keys(data[e]).forEach(function(a) {
if(!that[a]) {
that[a] = {id: a, [e]: data[e][a]}
result.push(that[a])
} else {
Object.assign(that[a], {[e]: data[e][a]})
}
})
}, {})
console.log(JSON.stringify(result, 0, 4))
答案 1 :(得分:1)
使用Array#reduce
的可能解决方案。
var obj = {"rank_type_1":{"d1":0,"d2":1,"d3":2},"rank_type_2":{"d1":1,"d2":0,"d3":2},"rank_type_3":{"d1":2,"d2":0,"d3":1}},
res = Object.keys(obj).reduce(function(s,a,i) {
var r = Object.keys(obj[a]).map((v, x) => ({["rank_type_"+[x+1]] : obj[a][v]}));
s.push(Object.assign({}, {id : "d"+(i+1)}, ...r));
return s;
}, []);
console.log(res);