简体   繁体   中英

Loop in JSON object and remove specific child

I have a json object from which i want to remove child having a key "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.

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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