我有这个Object/Array结构:

Obj = {
    "User": {
        "user1": [{
            "desc": "NG60",
            "Id": 3473631702,
            "Status": "offline"
        }],

        "user2": [{
            "desc": "somevalue",
            "Id": 963346121,
            "Status": "offline"
        },
        {
            "desc": "othervalue",  // SPLICE THIS OUT
            "Id": 963346122,      // SPLICE THIS OUT
            "Status": "offline"  // SPLICE THIS OUT
        }],

        "user3": [{
            "desc": "whatever",
            "Id": 972878784
        }]
    }
}


我想动态滤除不同的值(在此示例中已修复)
如果还没有ID,我想删除整个用户数组。

例如,如果要过滤出user2的第二个数组元素:

 for(var users in Obj) {
     for(var Ids in Obj[users]) {
         if(Obj[users][Ids].Id == 963346122){
             Obj[users][Ids].splice(0, 1); // ERROR HERE
         }
     }
     if(Obj[users][Ids] == undefined) {
         delete Obj[users];
     }
 }


我收到此错误:


  User [用户] [Ids] .splice(0,1)不是函数


如何只拼接我要寻址的数组元素,而不拼接整个user2数组?

最佳答案

如果没有剩余元素,请使用array.prototype.filter从数组中删除用户,并使用delete删除整个用户数组:

var obj = {
    "User": {
        "user1": [
          {
            "desc": "NG60",
            "Id": 3473631702,
            "Status": "offline"
          }
        ],
        "user2": [
          {
            "desc": "somevalue",
            "Id": 963346121,
            "Status": "offline"
          },
          {
            "desc": "othervalue",  // SPLICE THIS OUT
            "Id": 963346122,      // SPLICE THIS OUT
            "Status": "offline"  // SPLICE THIS OUT
          }
        ],
        "user3": [
          {
            "desc": "whatever",
            "Id": 972878784
          }
        ]
      }
    };

function deleteUser(id) {
    Object.keys(obj.User).forEach(user => {
        obj.User[user] = obj.User[user].filter(u => u.Id !== id);
        if (obj.User[user].length === 0) {
            delete obj.User[user];
        }
    });
}
deleteUser(963346121);
console.log(obj);
deleteUser(972878784);
console.log(obj);

关于javascript - Javascript:拼接多维对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47713882/

10-09 15:38