问题描述
我有以下对象:
object1 = [
{ title: "id",platformOne: value},{ title: "name",platformOne: name },{ title: "env",platformOne: env }
]
我想将其与其他人合并。相同的结构,相同的“标题”键,但紧随其后的是不同的键名:
object2 = [
{ title: "id",platformTwo: value},platformTwo: name },platformTwo: env }
]
我希望它看起来像这样:
object3 = [
{ title: "id",platformOne: value,platformOne: name,platformOne: env,platformTwo: env }
]
您能帮我吗?非常感谢。
解决方法
您可以这样操作:
const object3 = object1.map((obj,idx) => ({...obj,...object2[idx]}));
,
使用reduce
object1 = [
{ title: "id",platformOne: "value" },{ title: "name",platformOne: "name" },{ title: "env",platformOne: "env" },];
object2 = [
{ title: "id",platformTwo: "value" },platformTwo: "name" },platformTwo: "env" },];
arr = [object1,object2].flat();
res = arr.reduce((r,o) => {
if (!r[o.title]) r[o.title] = o;
else r[o.title] = { ...r[o.title],...o };
return r;
},{});
console.log(Object.values(res));
如果要简化上面的代码,可以使用三元运算符
object1 = [ { title: "id",];
object2 = [ { title: "id",object2].flat();
res = arr.reduce(
(r,o) => (
!r[o.title] ? (r[o.title] = o) : (r[o.title] = { ...r[o.title],...o }),r
),{}
);
console.log(Object.values(res));
,
您也可以使用它:
var object3 = [];
object1.forEach(function(item,index){
object3[index] = item;
object3[index].platformTwo = object2[index].platformTwo;
});