Sammy Kim
Sammy Kim

Reputation: 113

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]) == false) {
            renameKeys(obj[key], newKeys);
          }
          console.log(newKey, "]", obj[key]);
          return {
            [newKey]: obj[key],
          };
        });
        return Object.assign({}, ...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);

It look like all keys changed in function, but it is not applied . I think because of copy principal. I have no idea how I can manipulate for keys. I want to replace all keys so that I apply i18n in my code.

So new key will be somethign like
let newKey = i18n.$t(key); This short code is just for test code. Please give me some ideas to solve this problem.

Upvotes: 1

Views: 1876

Answers (2)

Nikhil Patil
Nikhil Patil

Reputation: 2540

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 -

function renameKeys(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];    
  });
  return Object.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);

Upvotes: 2

Kevin Zhang
Kevin Zhang

Reputation: 1092

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.

function renameKeys(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);

Upvotes: 0

Related Questions