提问者:小点点

合并具有不同属性名称的数组值


我有两个具有namevalueid的对象数组

阵列A

ArrayA:  [{
    name: ,
    value: ,
    key: 
},
];

我有另一个对象数组,但属性名称不同

ArrayB:  [{
    user: “userA” ,
    email: “emailA”,
    key:1: 
},
{
    user: “userB” ,
    email: “emailB”,
    key: 
},
];

现在我想让arraya拥有来自arrayb的值。 我意思是用户=>; 姓名和电子邮件=>; 价值

ArrayA应该有以下条目

  ArrayA:  [{
        name: “userA” ,
        value: “emailA”,
        key: 1
    },
        name: “userB” ,
        value: “emailB”,
        key: 1
    ]

我尝试使用map,但没有成功,知道我遗漏了什么吗?

ArrayA = ArrayB.map(((item: { name: string; value: string }) => (item.user, item.email))

我可以用一个循环,还有更好的方法来呢?

我应该用洛达什吗?


共3个答案

匿名用户

我认为arraya在这里是没有用的,您可以只在arrayb上使用map()并返回带有您需要的属性的数组。

null

const ArrayB = [
  {
    user: "dani" ,
    email: "dani@gmail.com",
    key:1 
  },
  {
    user: "john" ,
    email: "john@gmail.com",
    key:2
  }
]

const res = ArrayB.map(({ user, email, key }) => ({
  name: user,
  value: email,
  key 
}));

console.log(res);

匿名用户

最好使用扩展运算符和映射:

const result = [...ArrayA, ...ArrayB.map(({ key, user, email }) => ({ key, name: user, value: email }))]

匿名用户

必须使用数组concat()方法。

let ArrayA = [
    {
        name: 'name1',
        value: '22',
        key: 5,
    },
];

let ArrayB = [
    {
        name: 'name2',
        value: '33',
        key: 6,
    },
];

let ArrayC = ArrayA.concat(ArrayB);

let ArrayD = ArrayA.concat([{ name: 'name2' }, { value: '33' }, { key: 6 }]);


console.log(ArrayC);
console.log(ArrayA);
console.log(ArrayD); //ref sreenshot

你不能像你所指定的那样直接在数组中有元素,它们需要和一个对象有键值关系