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

128
Visualizações
How to change all key name inside nested array of objects javascript

I have nested array of objects like bellow:

const data = [
  {text: 'node 1'}, 
  {text: 'node 2', chapter_playlist: [{text: 'node 2-1', lesson_playlist: [{text: 'node 3-1'}]}]},
  {text: 'node 3'}, 
  {text: 'node 4', chapter_playlist: [{ text: 'node 4-1' }]}
]

How to rename each nested property like chapter_playlist, lesson_playlist to 'children' ?

basically I want to change the name of the property that has more children, if there are no children then there is no need to change it. And I'm still confused how to change it

expected results

const data = [
  {text: 'node 1'}, 
  {text: 'node 2', children: [{text: 'node 2-1', children: [{text: 'node 3-1'}]}]},
  {text: 'node 3'}, 
  {text: 'node 4', children: [{ text: 'node 4-1' }]}
]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Fun fact: if you need to walk through an object for whatever reason, JSON.stringify() is your friend.

Not because you want to turn your data into a JSON string, but because it's also an object iterator that lets you perform arbitrary processing at every level using a replacer function:

const data = [
  {text: 'node 1'}, 
  {text: 'node 2', chapter_playlist: [{text: 'node 2-1', lesson_playlist: [{text: 'node 3-1'}]}]},
  {text: 'node 3'}, 
  {text: 'node 4', chapter_playlist: [{ text: 'node 4-1' }]}
]

const rewriteList = [`chapter_playlist`, `lesson_playlist`];

function replacer(key, value) {
  // If the value at this depth is an object (but not an iterable
  // like array or Set or Map), then rebind the properties you
  // need rebound, provided they exist:
  if (typeof value === `object` && !value[Symbol.iterator]) {
    rewriteList.forEach(prop => {
      if (value[prop]) {
        // By editing "value", we're directly updating "data".
        value.children = value[prop];
        delete value[prop];
      }
    });
  }
  return value;
}

JSON.stringify(data, replacer);

console.log(data)

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