Search code examples
javascriptarraysjsonobjectnest

Best way for nest child objects from objects array with Javascript


Hi masters i need to find the best way to convert this:

 [
  { "id": 1, "animal": "cat", "age": 6, "name": "loky" },
  { "id": 2, "animal": "cat", "age": 3, "name": "michu", "parent": 1 },
  { "id": 3, "animal": "cat", "age": 2, "name": "boots", "parent": 1 },
  { "id": 4, "animal": "dog", "age": 9, "name": "bones" },
  { "id": 5, "animal": "dog", "age": 6, "name": "chok", "parent": 4 },
  { "id": 6, "animal": "dog", "age": 6, "name": "cofee","parent": 4 }
]

to this:

 [
  { "id": 1,
    "animal": "cat",
    "age": 6,
    "name": "loky",
    "childs":[ { "id": 2, "animal": "cat", "age": 3, "name": "michu", "parent": 1 },
               { "id": 3, "animal": "cat", "age": 2, "name": "boots", "parent": 1 }] 
  }
  ,
  { "id": 4,
    "animal": "dog",
    "age": 9,
    "name": "bones",
    "childs":[{ "id": 5, "animal": "dog", "age": 6, "name": "chok", "parent": 4 },
              { "id": 6, "animal": "dog", "age": 6, "name": "cofee", "parent": 4 }]
  }
 ]

note that the "parent" key must be used to nest "childs" ,i create my way but with several functions is horrible ,i think there may be a more efficient way.

Thanks in advance sorry for my english


Solution

  • const rows = [
      { id: 1, animal: 'cat', age: 6, name: 'loky' },
      { id: 2, animal: 'cat', age: 3, name: 'michu', parent: 1 },
      { id: 3, animal: 'cat', age: 2, name: 'boots', parent: 1 },
      { id: 4, animal: 'dog', age: 9, name: 'bones' },
      { id: 5, animal: 'dog', age: 6, name: 'chok', parent: 4 },
      { id: 6, animal: 'dog', age: 6, name: 'cofee', parent: 4 },
    ];
    
    function map(rows) {
      const categories = Array.from(new Set(rows.map((row) => row.animal)));
      return categories.map((c) => {
        const parent = rows.find((row) => row.animal === c);
        parent.childs = rows
          .filter((r) => r.id !== parent.id && r.animal === c)
          .map((r) => ({ ...r, parent: parent.id }));
        return parent;
      });
    }
    
    console.log(map(row));
    

    Simply create a mapper function to do.