JavaScript:删除对象内的数组元素

时间:2017-12-11 11:01:33

标签: javascript arrays object

此对象:

var Betreiber = {
      "user1": [
        {
          "desc": "60",
          "Id": 3473631702,
          "Status": "offline"
        },
        {
          "desc": "61",
          "Id": 3473631703,
          "Status": "offline"
        }

      ],
      "user2": [
        {
          "desc": "62",
          "Id": 963346121,
          "Status": "offline"
        },
        {
          "desc": "63", 
          "Id": 963346122,      
          "Status": "offline"  
        }
      ],
      "user3": [
        {
          "desc": "64",
          "Id": 972878784
        },
        {
          "desc": "65",
          "Id": 3473631706,
          "Status": "offline"
        }
      ]
  }

我的代码:

 var anlagen = [963346121, 963346122]; 

 for(var users in Betreiber) {
   for(var k=0;k<anlagen.length; k++) {
   for(var ids in Betreiber[users]) {
       if(anlagen[k] != Betreiber[users][ids].Id ){
         delete Betreiber[users][ids];
       }
     }
   }
   if(Betreiber[users].length === 0) {
     delete Betreiber[users];
   }
 }

我想拼接/删除不适合我的anlagen数组的每个元素。 出于某种原因,元素将被删除,但不会被完全删除。

例如:如果我只想保留user1的值:

状态:user1: [ , ], user2: [ , ], user3: [ , ]

所需:user1: [data....]

如果user.length为0,我不想删除整个用户。

2 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

&#13;
&#13;
var Betreiber = {
  "user1": [{
      "desc": "60",
      "Id": 3473631702,
      "Status": "offline"
    },
    {
      "desc": "61",
      "Id": 3473631703,
      "Status": "offline"
    }

  ],
  "user2": [{
      "desc": "62",
      "Id": 963346121,
      "Status": "offline"
    },
    {
      "desc": "63",
      "Id": 963346122,
      "Status": "offline"
    }
  ],
  "user3": [{
      "desc": "64",
      "Id": 972878784
    },
    {
      "desc": "65",
      "Id": 3473631706,
      "Status": "offline"
    }
  ]
};

var anlagen = [963346121, 963346122];

Object.keys(Betreiber).forEach(key => {
  Betreiber[key] = Betreiber[key].filter(item => {
    return anlagen.indexOf(item.Id) !== -1;
  });
  
  if(!Betreiber[key].length) {
    delete Betreiber[key];
  }
});

console.log(Betreiber);
&#13;
&#13;
&#13;

您只需使用Array#filter过滤掉不符合条件的元素即可。如果结果数组的长度为0,则可以从对象中删除其键。

答案 1 :(得分:1)

var anlagen = [963346121, 963346122]; 

for(var user in Betreiber) {
  for (var k = 0, len = anlagen.length; k < len; k++) {
   for (var j = 0, _len = Betreiber[user].length; j < _len; j++) {
     if (anlagen[k] != Betreiber[user][j].Id ) { 
       Betreiber[user].splice(j, 1);
     }
   }
  }
  if (Betreiber[user].length === 0) {
    delete Betreiber[user];
  }
}