2016-11-04 128 views
-4

将两个对象合并成一个。我有这样的阵列将两个对象合并到一个对象中。我有这个数组

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

在什么语言? – Randy

+0

在Javascript中,对不起,我忘记提及这 – sunnyn

+2

可能重复[我怎样才能动态合并两个JavaScript对象的属性?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-的,二,JavaScript的对象 - 动态地) –

回答

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))); 
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);