Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
Replace a special part of a JSON string

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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};
});
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!