JavaScript将一个新对象附加到对象数组中



嗨,试图为特定用户向汽车列表中添加一个新对象,下面是我的对象数组inventory。我用find来获取返回的用户id。

当用户id=1 时,我想向cars属性添加额外的对象,即{型号:"Porsche",年份:"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)

您可以使用排列运算符:

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
);

如果要在适当的位置修改数组,请使用Array.push。否则,分散运营商是一条出路:

const newInventory = [...inventory, {model: "Porsche",year: "2009"}];

您可以使用Array.prototype.map并更新id1的项。

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);

如果您不想创建新数组,则可以使用array.prototype.forEach而不是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);

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 addPropertyToCars=(id,newKeyValues)=>
inventory.map(item=>
item.id!==id ? item :{...item, cars:[...item.cars,newKeyValues]}
)

const newKeyValues={model: "Porsche",year: "2009"}
const newInventory=addPropertyToCars(1,newKeyValues)

最新更新