我在javascript中使用json对象文字。从我原来的json开始
[{"group":"sample 1","name":"FC_TOT","value":6},
{"group":"sample 1","name":"PPC","value":88},
{"group":"sample 1","name":"PRO_OX","value":6},
{"group":"sample 1","name":"POLY_TOT","value":6}],
[{"group":"sample 2","name":"FC_TOT","value":9},
{"group":"sample 2","name":"PPC","value":8},
{"group":"sample 2","name":"PRO_OX","value":7},
{"group":"sample 2","name":"POLY_TOT","value":7}]]
我需要根据名称对其进行重新排序,并为每个组分配值。新json应该看起来像
[
{
"group": "FC_TOT",
"sample 1": 6,
"sample 2": 9
},
{
"group": "PPC",
"sample 1": 88,
"sample 2":8
},
{
"group": "PRO_OX",
"sample 1": 6,
"sample 2": 7
},
{
"group": "POLY_TOT",
"sample 1": 6,
"sample 2": 7
}
]
其中新组是原始json的名称。任何想法如何实现这一目标?
答案 0 :(得分:1)
您可以使用reduce()
构建数组,并在一个forEach()
循环内循环对象。
var data = [[{"group":"sample 1","name":"FC_TOT","value":6},{"group":"sample 1","name":"PPC","value":88},{"group":"sample 1","name":"PRO_OX","value":6},{"group":"sample 1","name":"POLY_TOT","value":6}],[{"group":"sample 2","name":"FC_TOT","value":9},{"group":"sample 2","name":"PPC","value":8},{"group":"sample 2","name":"PRO_OX","value":7},{"group":"sample 2","name":"POLY_TOT","value":7}]]
var obj = {}
//Loop main array
var result = data.reduce(function(r, e) {
//Loop each group array to get objects
e.forEach(function(a) {
//Check if current object name exists as key in obj
if (!obj[a.name]) {
//If it doesn't create new object as its value and store it in obj
obj[a.name] = {group: a.name,[a.group]: a.value}
//push value of that object in result array of reduce or r
r.push(obj[a.name])
} else {
//If it already exists in obj then assign new property to it
Object.assign(obj[a.name], {[a.group]: a.value})
}
})
// Return accumulator or result array
return r;
}, [])
console.log(result)