2

I'm writing JavaScript code in which I want to replace a string in JSON object and my code is as below.

var obj = {
  "name": "name is $name",
  "work": "$name is doctor",
  "maritial status": "unmarried"
};

obj = Object.keys(obj).map(function(key, index) {
  return (obj[key].includes('$name')) ? obj[key].replace('$name', 'John'): obj[key];
});

console.log(obj);

Here I want to replace $name with John and print the JSON, but unfortunately, this is printing only the values like below instead of the whole JSON.

["name is John", "John is doctor", "unmarried"]

Where I am going wrong and how can I fix this?

3 Answers 3

4

You keep mentioning JSON but what you have is a JavaScript object. JSON is a string. So it would be much easier for you to keep it as a string, do a simple replace on the name, and then parse it to an object.

const json = '{"name":"name is $name","work":"$name is doctor", "maritial status":"unmarried"}';

const updated = json.replaceAll('$name', 'John');

console.log(JSON.parse(updated));

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to get a transformed object as the result, either assign the changed value to the original object:

var obj = {
  "name": "name is $name",
  "work": "$name is doctor",
  "maritial status": "unmarried"
};

Object.keys(obj).forEach(function(key) {
  if (obj[key].includes('$name')) {
    obj[key] = obj[key].replace('$name', 'John');
  }
});

console.log(obj);

Or use Object.entries and Object.fromEntries to map to a new object:

var obj = {
  "name": "name is $name",
  "work": "$name is doctor",
  "maritial status": "unmarried"
};
const newObj = Object.fromEntries(
  Object.entries(obj).map(([key, val]) => [key, val.replace('$name', 'John')])
);

console.log(newObj);

Comments

1

You can use Object.entries method or other object methods to solve your problem one of them might be ...

let obj = {
  "name": "name is $name",
  "work": "$name is doctor",
  "maritial status": "unmarried"
};

Object.entries(obj).forEach(item => {
  if ((obj[item[0]].includes('$name'))) {
    item[1] = item[1].replace("$name", "John");
    obj[item[0]] = item[1];
  }
})
console.log(obj);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.