【问题标题】:How do I delete the object? [duplicate]如何删除对象? [复制]
【发布时间】:2023-03-16 00:14:01
【问题描述】:

为什么数组中有一个未定义的?如何删除对象?

arr = [
  {id:1,name:'aaa'},
  {id:2,name:'bbb'},
  {id:3,name:'ccc'}
];

for(var item in arr){
  if(arr.hasOwnProperty(item)){
    if(arr[item].id === 2){
      delete(arr[item]);
      continue;
    }
  }
}

console.log(arr);

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    希望这是你想要做的:-

    var arr = [
      {id:1,name:'aaa'},
      {id:2,name:'bbb'},
      {id:3,name:'ccc'}
    ];
    
    
    arr = arr.filter(function(item){
      return item.id != 2;
    });
    
    console.log(arr)

    【讨论】:

      【解决方案2】:

      因为delete 不排列索引。来自文档

      删除数组元素时,数组长度不受影响。 即使您删除数组的最后一个元素,这仍然成立

      要删除,您需要使用 Array#splice 函数,该函数按索引删除。首先使用 Array#findIndex 找到索引,然后传递给拼接函数。

      arr = [
        {id:1,name:'aaa'},
        {id:2,name:'bbb'},
        {id:3,name:'ccc'}
      ];
      
      const index = arr.findIndex(item => item.id === 2);
      arr.splice(index, 1);
      console.log(arr);

      【讨论】:

        【解决方案3】:

        您需要修改arr,它是对象数组。delete 运算符从对象中删除给定属性,在您的情况下,您需要在删除对象后移动元素

        var arr = [{
            id: 1,
            name: 'aaa'
          },
          {
            id: 2,
            name: 'bbb'
          },
          {
            id: 3,
            name: 'ccc'
          }
        ];
        // iterating the object
        arr.forEach(function(item, index) {
          //checking if id === 2, if it is 2 using splice 
        //method to remove element from that index, & shift by one element
          if (item.id === 2) {
            arr.splice(index, 1)
          }
        })
        
        console.log(arr);

        【讨论】:

          猜你喜欢
          • 2023-03-24
          • 1970-01-01
          • 2019-10-29
          • 2018-05-27
          • 2016-02-28
          • 2011-03-28
          • 1970-01-01
          相关资源
          最近更新 更多