如何在反应状态下从数组内部的对象中删除属性

时间:2020-01-28 09:51:59

标签: javascript reactjs

如何以React状态从数组内部的对象中删除属性?

我遇到了错误:

Kim.tsx:150未捕获的TypeError:documents.forEach不是函数

代码:

  // Function to remove Mark as Reviewed property from objects inside the document array
  public hideMarkAsReviewed() {

      // Creates new array of objects
      let documents = {...this.state.documents};

      // Deletes property from all objects in array
      documents.forEach(d => { delete d['Mark as Reviewed'] });

      // Updates document state with the object
      this.setState({documents: documents});

  }

3 个答案:

答案 0 :(得分:2)

我认为这是您感到困惑的地方:

      // Creates new array of objects
      let documents = {...this.state.documents};

它不会创建新的对象数组,而是创建一个对象对象,其中的键将是索引。

      // Creates new array of objects
      let documents = [...this.state.documents];

数组使用方括号,并且Array类型具有forEach原型。

答案 1 :(得分:1)

这是删除数组中所有对象的特定属性的方法。

let array = [{name: "this is name1", title:"This is title 2"},{name:"this is name2", title:"This is title1"}];

let newArray = array.map(function(item) { 
    delete item.name; 
    return item; 
});
console.log(newArray)

答案 2 :(得分:1)

唯一的方法是使用过滤器从数组中删除元素,例如

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);