我有一个JSON数据
let data = [
{ "Id": 1, "Name": "Test", "Datacol1": "1", "Datacol2": 0,"Datacol3": 0 },
{ "Id": 2, "Name": "Test123", "Datacol1": "1", "Datacol2": 2, "Datacol3": 0 },
{ "Id": 1, "Name": "Test", "Datacol1": "0", "Datacol2": 1, "Datacol3": 0 },
{ "Id": 1, "Name": "Test", "Datacol1": "0", "Datacol2": 0, "Datacol3": 2 }
]
我想合并数据并将其基于Id放入单行数据中,例如Output =
[{"Id":1,"Name":"Test","Datacol1":"1","Datacol2":1,"Datacol3":2},
{"Id":2,"Name":"Test123","Datacol1":"1","Datacol2":2,"Datacol3":0}]
有人可以帮助我实现这一目标吗?
答案 0 :(得分:0)
使用数组reduce
和findIndex
。在内部还原中,使用findIndex
检查数组是否包含id
匹配的对象。如果匹配,则检查其他任何键值是否为0。如果为零,则使用非零值进行更新。
let data = [{
"Id": 1,
"Name": "Test",
"Datacol1": "1",
"Datacol2": 0,
"Datacol3": 0
},
{
"Id": 2,
"Name": "Test123",
"Datacol1": "1",
"Datacol2": 2,
"Datacol3": 0
},
{
"Id": 1,
"Name": "Test",
"Datacol1": "0",
"Datacol2": 1,
"Datacol3": 0
},
{
"Id": 1,
"Name": "Test",
"Datacol1": "0",
"Datacol2": 0,
"Datacol3": 2
}
]
let m = data.reduce(function(acc, curr) {
let findId = acc.findIndex((item) => {
return item.Id === curr.Id;
});
if (findId === -1) {
acc.push(curr)
} else {
for (let keys in acc[findId]) {
if (acc[findId][keys] === 0) {
acc[findId][keys] = curr[keys]
}
}
}
return acc;
}, []);
console.log(m)