将重复条目限制为数组JavaScript

索迈·保罗

我试图将对象作为元素添加到数组中。我可以限制第一个已经添加的元素,但后续条目将被复制。

这是代码:

onAddButtonPress(data, id, name){
  const items = this.props.items;

  if(items.length >= 1){
    items.forEach(i=>
      {
        if(i.id !== id){
          const arr = data.map(i=>{
            return i.name
          })
    this.props.addToShopList({id:id, arr:arr, name:name})
        }
      }
      )

  }
  else{
    const arr = data.map(i=>{
      return i.name
    })
  this.props.addToShopList({id:id, arr:arr, name:name})
  }     

}

如何停止重复的条目?请提出建议。谢谢!

罗比·科尼利森(Robby Cornelissen)

您是从循环内部添加到列表的,这似乎不正确。还有许多不必要的检查和重复的代码。

使用Array.prototype.some()以下命令就足够了

onAddButtonPress(data, id, name) {
  const items = this.props.items;

  if (!items.some(i => i.id === id)) {
    const arr = data.map(({name}) => name);
    this.props.addToShopList({id, arr, name});
  }
}

完整的课程示例:

class Test {
  constructor() {
    this.props = {
      items: [],
      addToShopList: (item) => this.props.items.push(item)
    };
  }
  
  onAddButtonPress(data, id, name) {
    const items = this.props.items;

    if (!items.some(i => i.id === id)) {
      const arr = data.map(({name}) => name);          
      this.props.addToShopList({id, arr, name});
    }
  }
}

const test = new Test();
test.onAddButtonPress([], 1, "One");
test.onAddButtonPress([], 2, "Two");
test.onAddButtonPress([], 2, "Two");

console.log(test.props.items);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章