admin管理员组文章数量:1335588
I want to add some text at the start of each json object key.
Object.keys(json).forEach(key => {
json = json.replace(key, `_${key}`);
});
I'm trying this method but it changes some values instead of adding _ at the start of each key.
I want to add some text at the start of each json object key.
Object.keys(json).forEach(key => {
json = json.replace(key, `_${key}`);
});
I'm trying this method but it changes some values instead of adding _ at the start of each key.
Share Improve this question asked Dec 14, 2017 at 10:56 afaqafaq 1094 silver badges13 bronze badges 7- 2 How does your JSON look like? – bamtheboozle Commented Dec 14, 2017 at 10:57
-
is
json
is a string or aobject
? – Koushik Chatterjee Commented Dec 14, 2017 at 10:58 - its a json formate, I've stringfy it – afaq Commented Dec 14, 2017 at 10:59
-
1
if its stringified, then you can't do
Object.keys(json)
– Koushik Chatterjee Commented Dec 14, 2017 at 11:00 -
so none of your key already has a starts with
_
right? – Koushik Chatterjee Commented Dec 14, 2017 at 11:02
1 Answer
Reset to default 10You are going right. You have to iterate over Object.keys
and inside each iteration assign a new key with same value and delete the previous key.
Here we are appending a -
before each key.
function modifyKeys(obj){
Object.keys(obj).forEach(key => {
obj[`_${key}`] = obj[key];
delete obj[key];
if(typeof obj[`_${key}`] === "object"){
modifyKeys(obj[`_${key}`]);
}
});
}
var jsonObj = {a:10, b:{c:{d:5,e:{f:2}}, g:{}},i:9};
modifyKeys(jsonObj);
console.log(jsonObj);
本文标签: javascripthow to change each key of json objectStack Overflow
版权声明:本文标题:javascript - how to change each key of json object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742384781a2464811.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论