简体   繁体   English

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

[英]Loop in JSON object and remove specific child

I have a json object from which i want to remove child having a key "errMsg". 我有一个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"}]}

result i want is the JSON should only have the child which doesn't have "errorMsg" in it. 我想要的结果是JSON应该只有没有“errorMsg”的子节点。

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

code i used 我使用的代码

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];
            }
        }

Not working for me. 不适合我。

try this it will filter your array and will result your needed data as result 试试这个它会过滤你的数组,并将结果你需要的数据

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)

To assing it back use 协助它重新使用

jsonData.info = result; jsonData.info =结果;

try this in your console :) enjoy 在你的控制台尝试这个:)享受

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM