How to generate child keys by parent keys in array JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have an array of objects like this −

const arr = [
   { id: 1, parent_id: 0, title: 'Movies' },
   { id: 2, parent_id: 0, title: 'Music' },
   { id: 3, parent_id: 1, title: 'Russian movies' },
   { id: 4, parent_id: 2, title: 'Russian music' },
   { id: 5, parent_id: 3, title: 'New' },
   { id: 6, parent_id: 3, title: 'Top10' },
   { id: 7, parent_id: 4, title: 'New' },
   { id: 8, parent_id: 4, title: 'Top10' },
   { id: 9, parent_id: 0, title: 'Soft' }
];

We are required to write a function that takes in this array and returns a new array of object with each object having an extra property “child” which must be an array of all the ids of object which are direct or indirect child of a particular object.

Therefore, the output should look like −

[
   { id: 1, parent_id: 0, title: 'Movies', childs: [ 3, 5, 6 ] },
   { id: 2, parent_id: 0, title: 'Music', childs: [ 4, 7, 8 ] },
   { id: 3, parent_id: 1, title: 'Russian movies', childs: [ 5, 6 ] },
   { id: 4, parent_id: 2, title: 'Russian music', childs: [ 7, 8 ] },
   { id: 5, parent_id: 3, title: 'New', childs: [] },
   { id: 6, parent_id: 3, title: 'Top10', childs: [] },
   { id: 7, parent_id: 4, title: 'New', childs: [] },
   { id: 8, parent_id: 4, title: 'Top10', childs: [] },
   { id: 9, parent_id: 0, title: 'Soft', childs: [] }
]

Now, let’s write the code for this function −

Example

const arr = [
   { id: 1, parent_id: 0, title: 'Movies' },
   { id: 2, parent_id: 0, title: 'Music' },
   { id: 3, parent_id: 1, title: 'Russian movies' },
   { id: 4, parent_id: 2, title: 'Russian music' },
   { id: 5, parent_id: 3, title: 'New' },
   { id: 6, parent_id: 3, title: 'Top10' },
   { id: 7, parent_id: 4, title: 'New' },
   { id: 8, parent_id: 4, title: 'Top10' },
   { id: 9, parent_id: 0, title: 'Soft' }
];
const generateChild = arr => {
   return arr.reduce((acc, val, ind, array) => {
      const childs = [];
      array.forEach((el, i) => {
         if(childs.includes(el.parent_id) || el.parent_id === val.id){
            childs.push(el.id);
         };
      });
      return acc.concat({...val, childs});
   }, []);
};
console.log(generateChild(arr));

Output

The output in the console will be −

[
   { id: 1, parent_id: 0, title: 'Movies', childs: [ 3, 5, 6 ] },
   { id: 2, parent_id: 0, title: 'Music', childs: [ 4, 7, 8 ] },
   { id: 3, parent_id: 1, title: 'Russian movies', childs: [ 5, 6 ] },
   { id: 4, parent_id: 2, title: 'Russian music', childs: [ 7, 8 ] },
   { id: 5, parent_id: 3, title: 'New', childs: [] },
   { id: 6, parent_id: 3, title: 'Top10', childs: [] },
   { id: 7, parent_id: 4, title: 'New', childs: [] },
   { id: 8, parent_id: 4, title: 'Top10', childs: [] },
   { id: 9, parent_id: 0, title: 'Soft', childs: [] }
]
raja
Published on 26-Aug-2020 11:50:38
Advertisements