Abhinav Parashar Abhinav Parashar - 7 months ago 23
Javascript Question

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.

Answer Source

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