合并角度为6的两个对象数组

时间:2018-07-11 10:21:46

标签: javascript arrays json angular

我有两个类似这样的数组。

array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}]

结果应该是这样的。

array3 = [{name: 'arjun', place:'mysore', degree:'BE'}, {name:'kanka',place:'bangalore',degree:'MCA'}];

上面的结果数组现在没有重复的值。有人可以帮忙吗?

6 个答案:

答案 0 :(得分:2)

您可以简单地使用Array.map()Object.assign()

array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}];

let result = array1.map((a)=>{
 let obj2 = array2.find((b)=> a.name === b.name);
 if(obj2)
  Object.assign(a,obj2);
 return a;
});

console.log(result);

答案 1 :(得分:1)

像这样使用foreach

let array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
let array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}]


let array3 = [];

array1.forEach((item, index) => {
    array3.push(item)
    let degree = array2.find(e => e.name === item.name)
    if(degree){
      array3[index].degree = degree.degree
    }
})

console.log(array3)

答案 2 :(得分:1)

假设您需要按index合并数组并且属于same length

let array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
let array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}]

let array3 = array1.map((o,i) => ({...o, ...array2[i]}));
console.log(array3);

答案 3 :(得分:1)

如果两个数组的长度相同,则此解决方案将起作用。

array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}]

const array3 = [];
for(let i=0; i < array1.length; i++){
    array3.push(Object.assign(array1[i], array2[i]));
}
console.log(array3);

工作JSBin here

也可以在这里查看:How can I merge properties of two JavaScript objects dynamically?

答案 4 :(得分:1)

我认为您可以使用array#reduce做类似的事情:

array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}]

var resultArray = array1.reduce((arr, e) => {
  arr.push(Object.assign({}, e, array2.find(a => a.name == e.name)))
  return arr;
}, [])


console.log(resultArray);

注意:如果这些数组的长度不同,它也将起作用。

答案 5 :(得分:1)

您可以使用namereduce通过map进行属性聚合,将聚合后的数据存储到一个数组中:

const array1 = [{name:'arjun', place:'mysore'},{name:'kanka', place:'bangalore'}];
const array2 = [{name: 'arjun', degree:'BE'},{name:'kanka', degree:'MCA'}];

const objData = [...array1, ...array2].reduce((all, { name, place, degree }) => {

    if (!all.hasOwnProperty(name)) all[name] = { name };
    if (place) all[name].place = place;
    if (degree) all[name].degree = degree;

    return all;

}, {});

const result = Object.keys(objData).map(k => objData[k]);

console.log(result);