如何将数组元素作为键值对添加到对象数组中

问题描述 投票:0回答:1

I want to add key value pair to object array

from this array

最终数组应该有 uniqueIds

const characters = [
{
name: "Luke Skywalker",
height: "172",
mass: "77",
eye_color: "blue",
gender: "male",
},
{
name: "Darth Vader",
height: "202",
mass: "136",
eye_color: "yellow",
gender: "male",
},
{
name: "Leia Organa",
height: "150",
mass: "49",
eye_color: "brown",
gender: "female",
},
{
name: "Anakin Skywalker",
height: "188",
mass: "84",
eye_color: "blue",
gender: "male",
},
];
att = ["B0117", "B5019", "B0821", "B0098"\];
attArr = characters.map((tim) => {
return { ...tim, UniqueId: "B0117" }
});
console.log(attArr);

我想将数组(att)中的元素作为 uniqueID 添加到对象数组中

name: 'Anakin Skywalker',
height: '188',
mass: '84',
eye_color: 'blue',
gender: 'male',
UniqueId: 'B0117'

所有四个元素都应映射到 UniqueID uniqueId 应该具有数组中的值。

我想将其作为键值对插入[(https://www.stackoverflow.com/)

att = ["B0117", "B5019", "B0821", "B0098"];
attArr = characters.map((tim) => {
  return { ...tim, UniqueId: "B0117" }
});
console.log(attArr);
arrays javascript-objects
1个回答
0
投票

你的方向是正确的,你只需要将索引传递给

att
arr i。
att[index]

const attArr = characters.map((character, index) => {
  return { ...character, UniqueId: att[index] };
});

console.log(attArr);

代码将按以下方式分配唯一 ID:

  • attArr 中的第一个字符将具有“B0117”的 UniqueId,因为 att[0] 是“B0117”。
  • attArr 中的第二个字符将有一个 “B5019”的 UniqueId 因为 att[1] 是“B5019”等等,
© www.soinside.com 2019 - 2024. All rights reserved.