Javascript 合并角度为6的两个对象数组
我有两个类似这样的数组Javascript 合并角度为6的两个对象数组,javascript,arrays,json,angular,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',deg
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'}];
结果应该是这样的
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'}];
上面的结果数组现在没有重复的值。有人能帮忙吗?您只需使用
Array.map()
和Object.assign()
array1=[{姓名:'arjun',地点:'mysore'},{姓名:'kanka',地点:'bangalore'}];
array2=[{name:'arjun',degree:'BE'},{name:'kanka',degree:'MCA'}];
让结果=数组1.map((a)=>{
让obj2=array2.find((b)=>a.name==b.name);
如果(obj2)
分配对象(a,obj2);
返回a;
});
控制台日志(结果)代码>像这样使用foreach
let array1=[{姓名:'arjun',地点:'mysore'},{姓名:'kanka',地点:'bangalore'}];
设array2=[{name:'arjun',degree:'BE'},{name:'kanka',degree:'MCA'}]
设数组3=[];
数组1.forEach((项目、索引)=>{
阵列3.推送(项目)
让degree=array2.find(e=>e.name==item.name)
if(学位){
数组3[索引]。度=度。度
}
})
console.log(array3)
假设您需要通过索引合并数组,并且数组长度相同
let array1=[{姓名:'arjun',地点:'mysore'},{姓名:'kanka',地点:'bangalore'}];
设array2=[{name:'arjun',degree:'BE'},{name:'kanka',degree:'MCA'}]
设array3=array1.map((o,i)=>({…o,…array2[i]}));
控制台日志(array3)代码>如果两个数组的长度相同,则此解决方案将起作用
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);
array1=[{姓名:'arjun',地点:'mysore'},{姓名:'kanka',地点:'bangalore'}];
array2=[{name:'arjun',degree:'BE'},{name:'kanka',degree:'MCA'}]
常量数组3=[];
for(设i=0;i
工作
看看这里:我想你可以用它来做这样的事情,也许:
array1=[{姓名:'arjun',地点:'mysore'},{姓名:'kanka',地点:'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)))
返回arr;
}, [])
console.log(resultArray)
您可以使用reduce
和通过名称对属性进行聚合,并将聚合数据映射到数组中:
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);
到目前为止,您尝试了什么?数组的长度是否相同?同样的订单?