删除嵌套在JSON中的项目

时间:2017-09-04 15:03:08

标签: javascript arrays json object

我有一些嵌套在JSON中的项目。

我有要删除的项目的ID。

我该怎么做?例如,使用JavaScript

删除使用ID为1的John

以下是JSON的示例; -

[  
   [  
      {  
         "ID":1,
         "firstname":"John",
         "surname":"Doe",
         "email":"john.doe@email.com"
      }
   ],
   [  
      {  
         "ID":2,
         "firstname":"Jane",
         "surname":"Doe",
         "email":"jane.doe@email.com"
      }
   ]
]

2 个答案:

答案 0 :(得分:0)

您可以使用反向for循环创建递归函数,并且当找到具有相同ID的元素时,使用splice将其删除。

var data = [[{"ID":1,"firstname":"John","surname":"Doe","email":"john.doe@email.com"},{"ID":1,"firstname":"John","surname":"Doe","email":"john.doe@email.com"},[[[{"ID":3,"firstname":"John","surname":"Doe","email":"john.doe@email.com"}]]]],{"ID":1,"firstname":"Jane","surname":"Doe","email":"jane.doe@email.com"},[{"ID":2,"firstname":"Jane","surname":"Doe","email":"jane.doe@email.com"}]]

let findAndDelete = function(data, id) {
  var length = data.length;
  for(var i = length; i >= 0; i--) {
    if(typeof data[i] == 'object') {
      if(data[i].ID == id) data.splice(i, 1);
      if(Array.isArray(data[i])) findAndDelete(data[i], id);
    }
  }
}

findAndDelete(data, 1);
console.log(data)

更新:您还可以使用filter()find()

var data = [[{"ID":1,"firstname":"John","surname":"Doe","email":"john.doe@email.com"}],[{"ID":2,"firstname":"Jane","surname":"Doe","email":"jane.doe@email.com"}]]

var result = data.filter(function(e) {
  return !e.find(o => o.ID == 1);
})

console.log(result)

答案 1 :(得分:0)

这将根据ID删除JSON中的对象。

function removeItem(itemID,jsonStr) {
    var jsonObj = JSON.parse(jsonStr);
    var compactJsonObj = [];

    for (var i = 0; i < jsonObj.length; ++i) {
        if (jsonObj[i][0].ID === itemID) {
            delete jsonObj[i];
        }
    }

    for (var i = 0; i < jsonObj.length; ++i) {
        if (jsonObj[i]) {
            compactJsonObj.push(jsonObj[i]);
        }
    }

    return JSON.stringify(compactJsonObj);
}