admin管理员组文章数量:1310526
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);
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?
Share Improve this question edited Sep 22, 2021 at 21:46 halfer 20.5k19 gold badges109 silver badges202 bronze badges asked Sep 6, 2021 at 20:12 RakeshRakesh 5941 gold badge10 silver badges27 bronze badges3 Answers
Reset to default 4You 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));
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);
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);
本文标签: javascriptReplace a variable in JSON objectStack Overflow
版权声明:本文标题:javascript - Replace a variable in JSON object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741794500a2397854.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论