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 a object? – 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
 |  Show 2 more ments

1 Answer 1

Reset to default 10

You 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