ES6:如何在添加重复值的同时在数组中推送唯一值?

时间:2018-09-14 05:22:18

标签: ecmascript-6

我有一个对象数组,如:

[
  {
    "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 个答案:

答案 0 :(得分:2)

伪代码:
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)
}