如何向数组中的现有对象添加新值

How to add a new value to existing object in array

如何向数组中的对象添加值 persons

我要添加的值是 lastname,变量 id 是要添加值的对象的 ID。


const lastname = 'Jackson';
const id = 2;

const persons = [
    {
        id: 1
        firstname: 'Mary',
        lastname: 'Jackson'
    },

    {
        id: 2
        firstname: 'Ash'
    }
]
persons.forEach(person => {
    if(this.id === person.id) person.lastname = this.lastname
})

您需要遍历数组并添加一个条件来检查 id 是否匹配 person.id 然后将 lastname 添加到那个人对象。如果您不想更改原始数组,请选择 .map() else .forEach() 随着 .forEach():

persons.forEach(person => {
  if (person.id === id) {
    person.lastname = lastname
  }
})

.map():

const newPersonsArr = persons.map(person => {
  if (person.id === id) {
    return {
      ...person,
      lastname
    }
  }
  return person;
})

这是在不改变原始数组的情况下对其进行更新的单行代码:

const updatedPersons = persons.map(p => p.id === id ? {...p, lastname} : p);