Ahmad Ahmad - 2 years ago 63
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:


Expected results:


Answer Source

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download