Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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' }],
  },
];
about 4 years ago · Juan Pablo Isaza Relatório

0

Couldn't make it more simpler.

console.log(
  [{
      "id": 1,
      "name": "foo",
      "Organization": [{
        "team": "value1"
      }, {
        "location": "value2"
      }]
    },
    {
      "id": 2,
      "name": "foo",
      "Organization": [{
        "team": "value1"
      }, {
        "location": "value2"
      }]
    },
  ].reduce((a, b) => {
    b.Organization[0] = {
      teamName: b.Organization[0].team
    }
    a.push(b)
    return a
  }, [])
)

about 4 years ago · Juan Pablo Isaza Relatório

0

If Organization is always an array with 2 elements. Where the first element is an object with the property team, and the second element is an object with the property location. Then the following code does job.

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

const result = myArray.map((item) => {
  const [{ team: teamName }, location] = item.Organization;
  return { ...item, Organization: [{ teamName }, location] };
});

console.log(result);

This answer makes use of destructuring assignment. If you don't know what this is I would highly suggest checking out the linked documentation.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda