Search code examples
javascriptnested-loops

Changing the keys of a nested object in an Array with JavaScript


I need to change the keys of my object. I could use the map function to change the keys of my outer object. Question is, how can I access the inner object which is in an array as well. In the code below, I need to change the team key to teamName. My structure has to be in the same order.

let myArray = [
  {
    id: 1,
    name: "foo",
    Organization: [{ team: "value1" }, { location: "value2" }],
  },
  {
    id: 2,
    name: "foo",
    Organization: [{ team: "value1" }, { location: "value2" }],
  },
];

I can change the keys of the outer array like this if I want to change id to userId.

const newArray = myArray.map((item) => {
  return {
    userId: item.id,
  };
});

But trying to change the keys in the inner list of objects for Organization becomes a problem. What is the best way to modify the inner keys?


Solution

  • Option 1 - lodash mapKeys

    import { mapKeys } from 'lodash';
    
    const newArray = myArray.map(item => ({
      ...item,
      Organization: item.Organization.map(org =>
        mapKeys(org, (_, key) => (key === 'team' ? 'teamName' : key))
      ),
    }));
    

    Option 2 - object destruction

    You can destruct each Organization and reconstruct it with teamName, as long as team exists.

    const newArray = myArray.map(item => ({
      ...item,
      Organization: item.Organization.map(({ team, ...rest }) =>
        Object.assign(rest, team ? { teamName: team } : {})
      ),
    }));
    

    Result

    [
      {
        id: 1,
        name: 'foo',
        Organization: [{ teamName: 'value1' }, { location: 'value2' }],
      },
      {
        id: 2,
        name: 'foo',
        Organization: [{ teamName: 'value1' }, { location: 'value2' }],
      },
    ];