Leem.fin
Leem.fin

Reputation: 42582

How to flat array of objects which can contain nested objects in my case

I have a data with structure like this:

const arr1 = [
  {
    name: 'a',
    subObjects: [
      { name: 'a1', age: 10 },
      { name: 'a2', age: 12 },
    ],
  },
  { name: 'b', age: 23 },
  {
    name: 'c',
    subObjects: [
      { name: 'c1', age: 30 },
      { name: 'c2', age: 32 },
    ],
  },
  ...
];

So, the array contains an array of objects, some objects also contain nested level object subObjects which contains the same structure as parent. Overall some 1st level object in array can have maximum two levels of nest (like above example shows).

Now, I need to have an array that gather all names of objects from above array, something like:

[
  { name: 'a' },
  { name: 'a1' },
  { name: 'a2' },
  { name: 'b' },
  { name: 'c' },
  { name: 'c1' },
  { name: 'c2' },
];

This is what I tried:

const arr1 = [
  {
    name: 'a',
    subObjects: [
      { name: 'a1', age: 10 },
      { name: 'a2', age: 12 },
    ],
  },
  { name: 'b', age: 23 },
  {
    name: 'c',
    subObjects: [
      { name: 'c1', age: 30 },
      { name: 'c2', age: 32 },
    ],
  },
];

const arr2 = arr1.map((obj) => {
  return obj.subObjects ? obj.subObjects.flat() : obj.name;
});
console.log(arr2.flat());

But the output lost the 1st level object names for those who has nested objects. So, what is the best way to achieve what I need?

Upvotes: 1

Views: 112

Answers (1)

Jamiec
Jamiec

Reputation: 136074

You could use a recursive flatMap to do it (with a little help from the spread oparator!):

const arr1 = [{name: 'a', subObjects:[{name: 'a1', age: 10}, {name: 'a2', age: 12},]}, {name: 'b', age: 23}, {name: 'c', subObjects:[{name: 'c1', age: 30}, {name: 'c2', age: 32},]}];


const recursiveFlat = (arr) => arr.flatMap(
  a => a.subObjects 
          ? [{name: a.name}, ...recursiveFlat(a.subObjects)] 
          : {name: a.name});


console.log(recursiveFlat(arr1));

This will work with any depth of nesting.

Upvotes: 1

Related Questions