Skip to content Skip to sidebar Skip to footer

How Can I Replace All Keys Of Nested Object In Javascript

function renameKeys(obj, newKeys) { const keyValues = Object.keys(obj).map((key) => { let newKey = key + '1'; if (Array.isArray(obj[key]) == fa

Solution 1:

You need to define your function to create new key value pairs and then form an object from these. Also, check if the value is an object, to recursively rename nested objects -

functionrenameKeys(obj) {
  const keyValues = Object.entries(obj).map(([key, value]) => {
    let newKey = key + "1";
    if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
      value = renameKeys(value);
    }
    return [newKey, value];    
  });
  returnObject.fromEntries(keyValues);
}

test = JSON.parse(
'{"verifying_explanation": {"bus_stop": ["1234"],"elementary_school": ["1234"],"middle_school": ["1234"],"high_school": ["1234"]}}'
);
console.log(test);
data = renameKeys(test, this);
console.log(data);

Solution 2:

You can't return new key-value pair in your function, instead of that, you just need to add new key to obj and delete old one.

functionrenameKeys(obj, newKeys) {
        Object.keys(obj).map((key) => {
          let newKey = key + "1";
          if (Array.isArray(obj[key]) == false) {
            renameKeys(obj[key], newKeys);
          }
          // console.log(newKey, "]", obj[key]);
          obj[newKey]=obj[key];
          delete obj[key];
        });
      }

      test = JSON.parse(
        `{"verifying_explanation":
               {"bus_stop":["1234"],
                "elementary_school":["1234"],
                "middle_school":["1234"],
                "high_school":["1234"]
               }
         }`
      );
      
      console.log(test);
      data = renameKeys(test, this);
      console.log(test);

Post a Comment for "How Can I Replace All Keys Of Nested Object In Javascript"