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)
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"}];
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
);
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);