将两个对象合并为一个。我有这个数组
var input= [
{
code:"Abc",
a:10
},
{
code:"Abc",
a:11
},
{
code:"Abcd",
a:11
}
]
我需要输出为
[
{code:"Abc",a:[10,11]},
{code:"Abcd",a:[11]},
]
Please help
答案 0 :(得分:0)
function merge(anArray){
var i, len = anArray.length, hash = {}, result = [], obj;
// build a hash/object with key equal to code
for(i = 0; i < len; i++) {
obj = anArray[i];
if (hash[obj.code]) {
// if key already exists than push a new value to an array
// you can add extra check for duplicates here
hash[obj.code].a.push(obj.a);
} else {
// otherwise create a new object under the key
hash[obj.code] = {code: obj.code, a: [obj.a]}
}
}
// convert a hash to an array
for (i in hash) {
result.push(hash[i]);
}
return result;
}
-
// UNIT TEST
var input= [
{
code:"Abc",
a:10
},
{
code:"Abc",
a:11
},
{
code:"Abcd",
a:11
}
];
var expected = [
{code:"Abc",a:[10,11]},
{code:"Abcd",a:[11]},
];
console.log("Expected to get true: ", JSON.stringify(expected) == JSON.stringify(merge(input)));
答案 1 :(得分:0)
您需要合并具有相同code
的对象,因此,任务很简单:
var input = [
{
code:"Abc",
a:10
},
{
code:"Abc",
a:11
},
{
code:"Abcd",
a:11
}
];
// first of all, check at the code prop
// define a findIndexByCode Function
function findIndexByCode(code, list) {
for(var i = 0, len = list.length; i < len; i++) {
if(list[i].code === code) {
return i;
}
}
return -1;
}
var result = input.reduce(function(res, curr) {
var index = findIndexByCode(curr.code, res);
// if the index is greater than -1, the item was already added and you need to update its a property
if(index > -1) {
// update a
res[index].a.push(curr.a);
} else {
// otherwise push the whole object
curr.a = [curr.a];
res.push(curr);
}
return res;
}, []);
console.log('result', result);
&#13;