Ahmad Ahmad - 7 months ago 6
Javascript Question

Replace values in a string using JavaScipt

I want to replace all string values in below json string to empty string, true to false, and 1 to 0 in square brackets using JavaScipt.

Addition informatio: json string is placed in a string type variable.

NOTE: properties are dynamic. Meaning sometimes I could have MobilePhone and there will be a case that this property will be missing. So referencing the property name is not an option.

My JSON string:

{"MobilePhone":true,"ToDeleteIndex":1,"BusinessPhone":true,"ApplicantType":"HOLDER","Title":"Mr","FirstName":"Andrew","RemoveApplicant":[1,null]}


Expected results:

{"MobilePhone":false,"ToDeleteIndex":1,"BusinessPhone":false,"ApplicantType":"","Title":"","FirstName":"","RemoveApplicant":[0,null]}

Answer

Try this DEMO

var data = JSON.parse('{"MobilePhone":true,"ToDeleteIndex":1,"BusinessPhone":true,"ApplicantType":"HOLDER","Title":"Mr","FirstName":"Andrew","RemoveApplicant":[1,null]}');

for (prop in data) {
  if (data[prop] === true) {
    data[prop] = false;
  } else if (typeof data[prop] == 'string') {
    data[prop] = '';
  } else if (Array.isArray(data[prop])) {
   data[prop] = data[prop].map(function(el) { return (el == 1) ? el = 0 : el});
  }
}

document.write(JSON.stringify(data));