我有下面的对象数组。
如果找到产品inventory
,如何遍历它来更改unit_price
和name
,如果找不到name
,如何创建新产品。
例如,如果在my_product
中的名称为stool
,则该记录将被添加到数组中,但是如果name
是table
,则{产品inventory
的{1}}和unit_price
必须进行调整。
table
答案 0 :(得分:2)
又快又脏,答案可能更简洁。
let products = [
{
name: "chair",
inventory: 5,
unit_price: 45.99
},
{
name: "table",
inventory: 10,
unit_price: 123.75
},
{
name: "sofa",
inventory: 2,
unit_price: 399.50
}
];
let my_product = { name: "stool", inventory: 1, unit_price: 300 }
let found = products.findIndex((e) => e.name == my_product.name);
if (found === -1) {
products.push(my_product);
} else {
const index = products.findIndex((e) => e.name === my_product.name);
products[index].inventory = my_product.inventory;
products[index].unit_price = my_product.unit_price;
}
答案 1 :(得分:1)
使用find
在name
数组中找到products
。如果找到,请更新所需的属性,否则请推送到数组。
let products = [{
name: "chair",
inventory: 5,
unit_price: 45.99
},
{
name: "table",
inventory: 10,
unit_price: 123.75
},
{
name: "sofa",
inventory: 2,
unit_price: 399.50
}
];
let my_product = {
name: "table",
inventory: 1,
unit_price: 300
};
let found = products.findIndex((e) => e.name == my_product.name);
if (found === -1) {
products.push(my_product);
} else {
const index = products.findIndex((e) => e.name === my_product.name);
products[index].inventory = my_product.inventory;
products[index].unit_price = my_product.unit_price;
}
console.log(products);
答案 2 :(得分:0)
这是地图(docs)的完美用例,以产品名称作为关键字。它将为您处理所有事情。
let product = {};
product["stool"] = {inventory: 1, unit_price: 300}; // new object is created
product["stool"] = {inventory: 5, unit_price: 350}; // stool data is replaced
// to find object, just look it up by product name
let my_stool = product["stool"]; // will return 'undefined' if "stool" doesn't exist
答案 3 :(得分:0)
您可以使用forEach
遍历元素。如果name
匹配,则使用传播运算符合并两个对象。
let products = [
{
name: "chair",
inventory: 5,
unit_price: 45.99
},
{
name: "table",
inventory: 10,
unit_price: 123.75
},
{
name: "sofa",
inventory: 2,
unit_price: 399.50
}
];
let my_product = {name: "stool", inventory: 1, unit_price: 300}
let added = false;
products.forEach((x,i) => {
if(x.name === my_product.name){
added = true;
products[i] = {...x,...my_product};
}
})
if(!added){
products.push(my_product);
}
console.log(products)
答案 4 :(得分:-3)
遍历数组:
for (index in products) {
在每个索引处,检查名称:
if (products[index].name==='chair') {
...
如果已经找到“ chair”,还可以包含一个布尔标志。如果不是,并且索引位于products.length-1,则将新元素添加到对象中。