Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda