Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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' }]}
]

>Solution :

Fun fact: if you need to walk an object for whatever reason, and it’s a pure data object (not something with function bindings) then JSON.stringify() is your friend.

Not because you want to turn your data into a JSON string, but because it’s also an object walker 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.
  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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading