afaq
afaq

Reputation: 109

how to change each key of json object

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.

Upvotes: 3

Views: 4638

Answers (1)

Rohit Agrawal
Rohit Agrawal

Reputation: 1521

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

Upvotes: 10

Related Questions