Home > Blockchain >  How to change all key name inside nested array of objects javascript
How to change all key name inside nested array of objects javascript

Time:11-19

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

CodePudding user response:

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.
  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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related