简体   繁体   中英

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

I have a React app with an array of Objects. 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. The problem is, the function produces the wrong output.

This is the 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

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

I tried the ES6 filter method as follows

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. Just assign result of filter to 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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