遍历数组的对象

时间:2019-07-09 16:52:34

标签: javascript

我有下面的对象数组。 如果找到产品inventory,如何遍历它来更改unit_pricename,如果找不到name,如何创建新产品。 例如,如果在my_product中的名称为stool,则该记录将被添加到数组中,但是如果nametable,则{产品inventory的{​​1}}和unit_price必须进行调整。

table

5 个答案:

答案 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)

使用findname数组中找到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,则将新元素添加到对象中。