[removed] Remove an element from an array of objects

后端 未结 2 789
臣服心动
臣服心动 2020-12-22 01:14

I have an array of objects:

var items = [{ id: 1, text: \"test1\" }, { id: 2, text: \"test2\" }, { id: 3, text: \"test3\"}];

I have the fol

相关标签:
2条回答
  • 2020-12-22 01:54

    Traverse the array by using a plain loop and then remove the matching item by using splice():

    for( var i=0; i<items.length; i++ ) {
      if( items[i].id == itemToRemove.id ) {
        items.splice( i, 1 );  // remove the item
        break; // finish the loop, as we already found the item
      }
    }
    
    0 讨论(0)
  • 2020-12-22 01:58

    Use filter:

    items.filter(function (item) {
        return item.id !== 2 || item.text !== "text2";
    });
    

    It's generally not a good idea to mutate the original array or else I would recommend Sirko's answer. The filter method produces a whole new array. It doesn't mutate the original array.

    0 讨论(0)
提交回复
热议问题