Ecmascript 6 ES6:如何在添加重复值的同时在数组中推送唯一值?
我有一组对象,如:Ecmascript 6 ES6:如何在添加重复值的同时在数组中推送唯一值?,ecmascript-6,Ecmascript 6,我有一组对象,如: [ { "name": "Apple", "amount": 5 }, { "name": "Tomato", "amount": 10 } ] 要求是当我推一个像 { "name": "Apple", "amount": 10 } 预期结果: [ { "name": "Apple", "amount": 15 }, { "name": "Tomato", "amoun
[
{
"name": "Apple",
"amount": 5
},
{
"name": "Tomato",
"amount": 10
}
]
要求是当我推一个像
{
"name": "Apple",
"amount": 10
}
预期结果:
[
{
"name": "Apple",
"amount": 15
},
{
"name": "Tomato",
"amount": 10
}
]
但在推送唯一条目时,如{“name”:“Orange”,“amount”:15}
,结果数组应为:
[{"name":"Apple","amount":5},{"name":"Tomato","amount":10},{"name":"Orange","amount":15}]
伪代码:1) 检查条目是否存在
2) 获取索引
3) 如果存在,更新对象数组
3) 如果不存在,则将条目推送到对象数组
const x = [{"name":"Apple","amount":5},{"name":"Tomato","amount":10}]
const toPush = {"name":"Apple","amount":30}
//(1 & 2) it would return a value greater than or equal to 0 if it exist
var indx= x.findIndex(q=>q.name == toPush.name)
// 3
if( getIndex >= 0 ) {
x[indx] = toPush
}
// 4
else {
x.push(toPush)
}
张贴的问题似乎根本不包括解决问题的方法。StackOverflow希望您能这样做,因为您的尝试有助于我们更好地了解您的需求。请编辑问题以显示您已尝试过的内容,以便说明您在某个问题中遇到的具体问题。欲了解更多信息,请参阅,并采取。而不是向下的选民,但我想投票的原因可能是,这可以通过更好的方式实现,必须已经有了地址。我们应该寻找这样的职位,并关闭这一个