Home > Mobile >  Replace a special part of a JSON string
Replace a special part of a JSON string

Time:05-10

I have a JSON object called users like this:

[{"givenName":"helen","sn":"brown","phone":"44512","details":"512"},{{"givenName":"John","sn":"Doe","phone":"44600","details":"512"}]

I apply json.stringify method to convert this JavaScript object to a JSON string. Then, I use replace to replace 512 value with active. Here is my code to implement this:

var jsonUsers = JSON.stringify(users).replace(/512/g, 'active');

The problem is that when I use this code, it replaces all 512 with active (for example in my example, it changesdetails values and also it changes the phone value of the first person with something like 44active), but I want to apply this replacement only on the values of the details key, not on whole of the string (for example I don't want to check and replace the value of the phone). How can I do this?

CodePudding user response:

Don't try to replace parts of a JSON. Fix it while it's an object instead.

const arr = [{"givenName":"helen","sn":"brown","phone":"44512","details":"512"},{"givenName":"John","sn":"Doe","phone":"44600","details":"512"}];

for (const item of arr) {
  if (item.details === '512') {
    item.details = 'active';
  }
}
console.log(JSON.stringify(arr));

CodePudding user response:

const users = [{"givenName":"helen","sn":"brown","phone":"44512","details":"512"},{"givenName":"John","sn":"Doe","phone":"44600","details":"512"}]

Now use array.map()

const newArray = users.map(e => {
    return {...e, details: e.details==512 ? "active" : e.details};
});

CodePudding user response:

If you only want to replace the text from details property then no need to convert the whole object into a string. You can simply iterate over the array using Array.map() method and then replace the details property value based on the regex.

Try this :

const jsonObj = [{
  "givenName": "helen",
  "sn": "brown",
  "phone": "44512",
  "details": "512"
}, {
  "givenName": "John",
  "sn": "Doe",
  "phone": "44600",
  "details": "512"
}];

const res = jsonObj.map(obj => {
    obj.details = obj.details.replace(/512/g, 'active');
  return obj;
});

console.log(res);

  • Related