通过删除重复项清空JSON对象并将其归零并将它们合并到单个记录中
json数组看起来像这样:
var result =
[
{"id":"10035","occupation":null,"state":"FL"},
{"id":"10035","occupation":"doctor","state":null},
{"id":"10035","occupation":null,"state":null},
]
我想将记录合并为一个忽略所有空字段并将其作为单个记录。下面是我的预期输出:
[
{"id":"10035","occupation":"doctor","state":"FL"}
]
答案 0 :(得分:2)
您可以使用此ES6脚本执行此操作:
let data = [
{"id":"10035","occupation":null,"state":"FL"},
{"id":"10035","occupation":"doctor","state":null},
{"id":"10035","occupation":null,"state":null},
];
let result = Object.values(data.reduce ( (acc, {id, occupation, state}) => {
acc[id] = Object.assign({ id }, acc[id],
occupation && { occupation },
state && { state });
return acc;
}, {}));
console.log(result);
如果您的输入中有不同的id值,它仍会生成多条记录。如果其他属性有多个非空值,但对于相同的id,则只有最后一个属性存活。
Object.values
使用它的定义:
Object.values = Object.values || (o => Object.keys(o).map(k => o[k]));
答案 1 :(得分:0)
var final = {};
for (var i in result) {
for (var k in result[i]) {
if (result[i][k] && final[k] !== result[i][k]) {
final[k] = result[i][k];
}
}
}
console.log(final); // outputs: {id: "10035", state: "FL", occupation: "doctor"}
答案 2 :(得分:0)
这是一个简单易懂的示例,适用于具有任意数量属性的对象。
updateCalcs(event){
console.log(event);
}

答案 3 :(得分:0)
以下是在O(n)时间内完成此操作的方法:
filter (where useful is null)