循环在JSON对象中并删除特定的子对象

时间:2017-05-12 05:49:33

标签: javascript arrays json

我有一个json对象,我想要删除有一个键的孩子" errMsg"。

input JSON : {"info":[{"errorMsg":"Unable to find Vendor ","c2v":"some text"},{"errorMsg":"Unable to find Vendor ","c2v":"Some text"},{"errorMsg":"Unable to find Vendor","c2v":" Some text"},{"id":"1038578481","ven":"DEMOMA","c2v":" Some text"}]}

我想要的结果是JSON应该只有一个没有" errorMsg"在它。

output JSON i want : {"info":[{"id":"1038578481","ven":"DEMOMA","c2v":" Some text"}]}

我使用的代码

jsonKeyInfo = stringToJson(form.response); 
for(var i in jsonKeyInfo.info){
            if(jsonKeyInfo.info[i].errorMsg){
                errMsg = jsonKeyInfo.info[i].errorMsg;
                jsonKeyInfo.info.splice(i,1);
                err++;
            //  delete jsonKeyInfo.info[i];
            }
        }

不适合我。

2 个答案:

答案 0 :(得分:3)

尝试此操作会过滤您的数组,并将结果显示您需要的数据

var jsonData = {"info":[{"errorMsg":"Unable to find Vendor ","c2v":"some text"},{"errorMsg":"Unable to find Vendor ","c2v":"Some text"},{"errorMsg":"Unable to find Vendor","c2v":" Some text"},{"id":"1038578481","ven":"DEMOMA","c2v":" Some text"}]};

var result = jsonData.info.filter(i=>!i.errorMsg)

console.log(result)

协助使用

jsonData.info = result;

在你的控制台中尝试这个:)享受

答案 1 :(得分:0)



obj = {"info":[
  {"errorMsg":"Unable to find Vendor ","c2v":"some text"},
  {"errorMsg":"Unable to find Vendor ","c2v":"Some text"},
  {"errorMsg":"Unable to find Vendor","c2v":" Some text"},
  {"id":"1038578481","ven":"DEMOMA","c2v":" Some text"}
  ]}
  
  var changed = false;

obj.info = obj.info.filter((el)=> !( el.hasOwnProperty("errorMsg") && (changed = true) ));
console.log(obj);
console.log("Obj.info changed? " + changed);

changed = false;
obj2 = [
{"id":"1038578481","ven":"DEMOMA","c2v":" Some text"},
{"id":"1038578481","ven":"DEMOMA","c2v":" Some text"}
];

obj2.filter((el)=> !( el.hasOwnProperty("errorMsg") && (changed = true) ));
console.log("Obj2 changed? " + changed);