我有一个数组
[[{"qId":1.3,"id":1}],[{"qId":1.3,"id":2},{"qId":1.3,"id":3}, {"qId":1.4,"id":3}]]
我如何合并它们使它成为:
[{"qId":1.3,"id":[1,2,3]},{"qId":1.4,"id":[3]}]
我试过使用_.uniq,但是它没有按照它给我结构的方式工作。提前谢谢。
答案 0 :(得分:2)
您可以连接数组,然后遍历数组并使用临时对象和结果数组收集数据。
var array = [[{ "qId": 1.3, "id": 1 }], [{ "qId": 1.3, "id": 2 }, { "qId": 1.3, "id": 3 }, { "qId": 1.4, "id": 3 }]],
merged = function (array) {
var o = {}, r = [];
[].concat.apply([], array).forEach(function (a) {
if (!(a.qId in o)) {
o[a.qId] = { qId: a.qId, id: [] };
r.push(o[a.qId]);
}
o[a.qId].id.push(a.id);
});
return r;
}(array);
document.write('<pre>' + JSON.stringify(merged, 0, 4) + '</pre>');
&#13;
答案 1 :(得分:1)
你可以这样做:
var array = [
[{
"qId": 1.3,
"id": 1
}],
[{
"qId": 1.3,
"id": 2
}, {
"qId": 1.3,
"id": 3
}, {
"qId": 1.4,
"id": 3
}]
]
//flatten the array inside array into a single array
var flatten = [].concat.apply([], array);
var final = [];
flatten.forEach(function(a1) {
//check in the final list with the quid
var filtered = final.filter(function(f) {
return f.qId == a1.qId
});
if (filtered.length == 0) {
//if not present make an object with id
var grp = {
id: []
};
grp.qId = a1.qId;
final.push(grp);
} else {
//get first element of filtered
grp = filtered[0]
}
grp.id.push(a1.id);
})
console.log(final)
工作代码here