Home > Mobile >  Convert an array of objects into a nested array of objects with different keys
Convert an array of objects into a nested array of objects with different keys

Time:09-13

So i have an array with the below structure. how would i go about converting it to the nested array below.

[
   {mainCategory: 'Brand', slug: 'brand', value: 'Brand', label: 'Brand'},
   {category: 'Cat1', slug: 'cat1', value: 'Cat1', label: 'Cat1'},
   {subCategory: 'SubCat1', slug: 'subcat1', value: 'SubCat1', label: 'SubCat1'},
   {mainCategory: 'Type', slug: 'type', value: 'Type', label: 'Type'},
   {category: 'Cat2', slug: 'cat2', value: 'Cat2', label: 'Cat2'},
   {subCategory: 'SubCat2', slug: 'subcat2', value: 'Cat2', label: 'Cat2'},
]
[
   {label: 'Brand', options:
       [
         { label: Cat1, value: Cat1 }, 
         { label: SubCat1, value: SubCat1 } 
       ]
   },
   {label: 'Type', options:
       [
         { label: Cat2, value: Cat2 }, 
         { label: SubCat2, value: SubCat2 } 
       ]
   },
]

CodePudding user response:

Loop over the array elements. If it's a mainCategory object, create a new array element for the result. Otherwise, push the nested object onto the current result element's options array.

const input_data = [
   {mainCategory: 'Brand', slug: 'brand', value: 'Brand', label: 'Brand'},
   {category: 'Cat1', slug: 'cat1', value: 'Cat1', label: 'Cat1'},
   {subCategory: 'SubCat1', slug: 'subcat1', value: 'SubCat1', label: 'SubCat1'},
   {mainCategory: 'Type', slug: 'type', value: 'Type', label: 'Type'},
   {category: 'Cat2', slug: 'cat2', value: 'Cat2', label: 'Cat2'},
   {subCategory: 'SubCat2', slug: 'subcat2', value: 'Cat2', label: 'Cat2'},
];

const result = [];
let current;
input_data.forEach(obj => {
  if (obj.mainCategory) {
    current = {
      label: obj.mainCategory,
      options: []
    };
    result.push(current);
  } else {
    current.options.push({
      label: obj.label,
      value: obj.value
    });
  }
});

console.log(result);

  • Related