嗨,嘗試將新物件添加到特定用戶的汽車串列中,下面是我的名為庫存的物件陣列。我使用 find 來獲取回傳的用戶 ID。
當用戶 id = 1 時,我想向汽車屬性添加額外的物件,即 {model: "Porsche",year: "2009"} 到用戶陣列
有沒有更清潔的方法來做到這一點而不使用推送
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)
uj5u.com熱心網友回復:
如果要就地修改陣列,請使用Array.push
. 否則傳播運算子是要走的路:
const newInventory = [...inventory, {model: "Porsche",year: "2009"}];
uj5u.com熱心網友回復:
您可以使用擴展運算子:
const addNewObject = [...found.cars, {model: "Porsche",year: "2009"}];
這將為您提供與您的代碼相同的結果。
如果您想知道如何以inventory
不可變樣式更新 (這是您不喜歡的原因push
嗎?),您可以使用map
:
const updatedInventory = inventory.map(item =>
item.id === 1
? {...item, cars: [...item.cars, {model: "Porsche",year: "2009"}]}
: item
);
uj5u.com熱心網友回復:
您可以使用Array.prototype.map并更新具有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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491801.html
標籤:javascript 反应 函数式编程 javascript 对象
下一篇:常數是如何設定的?