简体   繁体   English

如何在 React 中删除对象数组中的多个项目?

[英]How to remove multiple items in an array of objects in React?

I have a React app with an array of Objects.我有一个带有对象数组的 React 应用程序。 I use a method to first, get a list of object ids and then remove the elements in the array by comparing them to the ids list.我使用一种方法首先获取 object id 列表,然后通过将数组中的元素与 id 列表进行比较来删除它们。 The problem is, the function produces the wrong output.问题是,function 产生错误的 output。

This is the function这是 function

var questionsToRemove = [3,5,6,7];

state.questionsData = [
    { order: 1, question: "q1" },
    { order: 2, question: "q2" },
    { order: 3, question: "q3" },
    { order: 4, question: "q4" },
    { order: 5, question: "q5" },
    { order: 6, question: "q6" },
    { order: 7, question: "q7" },
];

removeQuestion = () => {
    var questionssData = this.state.questionsData
    questionssData.forEach(each => {
        if (questionsToRemove.includes(each.order)) {
            questionssData.splice(questionssData.indexOf(each))
        }
    });
    this.setState({ questionsData: questionssData })
}

The above method produces wrong output as上述方法产生错误的 output 为

    { order: 1, question: "q1" },
    { order: 2, question: "q2" },
    { order: 4, question: "q4" },
    { order: 6, question: "q6" },

I tried the ES6 filter method as follows我尝试了ES6过滤方法如下

removeQuestion = () => {
    var questionssData = this.state.questionsData
    questionssData.filter(each => {
        return questionsToRemove.includes(each.order)
    });
    this.setState({ questionsData: questionssData })
}

But this produces the same original array without filtering anything.但这会产生相同的原始数组而不过滤任何内容。 How can I remove the selected objects from the array?如何从数组中删除选定的对象?

Method .filter of Array doesn't mutate the array, it create a new array with filtered value. Array 的方法.filter不会改变数组,它会创建一个具有过滤值的新数组。 Just assign result of filter to questionssData .只需将过滤器的结果分配给questionssData

 questionssData = questionssData.filter(each => {
      return !questionsToRemove.includes(each.order)
 });

You have to assign the filter result array to your variable.您必须将过滤器结果数组分配给您的变量。 Also in order to filter(remove), you have to return false from your method:此外,为了过滤(删除),您必须从您的方法中返回 false:

removeQuestion = () => {
    var questionssData = this.state.questionsData
    questionssData = questionssData.filter(each => {
        return !questionsToRemove.includes(each.order)
    });
    this.setState({ questionsData: questionssData })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM