【发布时间】:2023-04-01 07:40:01
【问题描述】:
我有一个对象,我正在推入数组,同时推入我需要限制重复项,如果属性有任何更改,则相应地更新数组?
[{
Id: "a134",
Name: "Name -",
Company: "001",
Product :"01"
quantity :1
},
{
Id: "a135",
Name: "Name -1",
Company: "002",
Product :"03"
quantity :2 -----> (Previous event.target.name)
},
{
Id: "a135",
Name: "Name -1",
Company: "002",
Product :"03"
quantity :3 ---> (current event.target.name)
}
]
如果我推入数组,可能有机会更新数量如何实现以下结果
[{
Id: "a134",
Name: "Name -",
Company: "001",
Product :"01"
quantity :1
},
{
Id: "a135",
Name: "Name -1",
Company: "002",
Product :"03"
quantity :3 ---> (current event.target.name)
}
]
现在我的代码是
if(event.target.value!='')
{
const searchObj = this.myList.find(({ Id,Product, Company }) => Product === index);
if (searchObj)
{
console.log('searchObj',searchObj);
resultVal = { ...searchObj, quantity:parseInt(event.target.value)};
if (!this.newProductList.some(e => e.Product === resultVal.Product))
{
this.newProductList.push(resultVal);
}
}
}
【问题讨论】:
-
也许使用
find而不是some。如果返回undefined,则它不在 productList 中,因此将对象推送到 productList。 ELSE返回找到的对象,给quantity加一 -
那么最好不要使用数组结构,而是使用普通对象,以
Id为键。
标签: javascript arrays object duplicates arr