js数组中增加另一个数组中的字段
时间: 2023-09-09 22:06:34 浏览: 53
如果你想在 JavaScript 数组中增加另一个数组中的字段,可以使用 `map()` 方法结合 `find()` 方法来实现,例如:
```javascript
// 定义一个原始数组
const originalArray = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
// 定义一个包含其他字段的数组
const otherArray = [
{ id: 1, age: 20 },
{ id: 2, age: 25 },
{ id: 3, age: 30 }
];
// 对原始数组进行遍历并且增加一个新字段
const newArray = originalArray.map(item => {
const otherItem = otherArray.find(otherItem => otherItem.id === item.id);
return {
...item,
age: otherItem.age // 新增的字段名为 age,值为另一个数组中相同 id 的元素的 age 字段
}
});
console.log(newArray);
```
在上面的代码中,我们使用了 JavaScript 中的 `map()` 方法对原始数组进行遍历,并且使用 `find()` 方法在另一个数组中查找与当前元素相同 id 的元素,然后将其 `age` 字段赋值给当前元素的 `age` 字段。最后,我们将遍历后的新数组输出到控制台中。