Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
JavaScript Append a new object to an array of objects

Hi trying to add a new object to the list of cars for particular user, below is my array of object called inventory. Ive used a find to get the user id which return.

I want to add extra objects to the cars property i.e {model: "Porsche",year: "2009"} to the user array when the user id = 1

Is there a cleaner way of doing this without using push

const inventory = [
  {
    id: 1,
    name: "Paul",
    cars: [
      {
        model: "Ford",
        year: "1995",
      },
      {
        model: "BMW",
        year: "2010",
      },
    ],
  },
  {
    id: 2,
    name: "Simon",
    cars: [
      {
        model: "Vauxhall",
        year: "2022",
      },
      {
        model: "VW",
        year: "2001",
      },
    ],
  },
];


const found = inventory.find(element => element.id == 1);

//console.log(found)
const addNewObject = found.cars.concat({model: "Porsche",year: "2009"})
console.log(addNewObject)

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

If you want to modify the array in-place, use Array.push. Otherwise spread operator is the way to go:

const newInventory = [...inventory, {model: "Porsche",year: "2009"}];
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the spread operator:

const addNewObject = [...found.cars, {model: "Porsche",year: "2009"}];

This will give you the same result as your code.

In case you want to know how to update the inventory in an immutable style (is this the reason why you don't like push?), you can use map:

const updatedInventory = inventory.map(item => 
 item.id === 1
   ? {...item, cars: [...item.cars, {model: "Porsche",year: "2009"}]}
   : item
);
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use Array.prototype.map and update the item that has an id of 1.

const inventory = [
  {
    id: 1,
    name: "Paul",
    cars: [
      { model: "Ford", year: "1995" },
      { model: "BMW", year: "2010" },
    ],
  },
  {
    id: 2,
    name: "Simon",
    cars: [
      { model: "Vauxhall", year: "2022" },
      { model: "VW", year: "2001" },
    ],
  },
];

const updatedInventory = inventory.map((item) =>
  item.id === 1
    ? { ...item, cars: item.cars.concat({ model: "Porsche", year: "2009" }) }
    : item
);

console.log(updatedInventory);

If you want don't want to create a new array, then you can use Array.prototype.forEach instead of map.

const inventory = [
  {
    id: 1,
    name: "Paul",
    cars: [
      { model: "Ford", year: "1995" },
      { model: "BMW", year: "2010" },
    ],
  },
  {
    id: 2,
    name: "Simon",
    cars: [
      { model: "Vauxhall", year: "2022" },
      { model: "VW", year: "2001" },
    ],
  },
];

inventory.forEach((item) => {
  if (item.id === 1) {
    item.cars.push({ model: "Porsche", year: "2009" });
  }
});

console.log(inventory);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda