Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert recursive array object to flat array object

I'm looking for a way to convert this array of recursive objects into a flat array of objects to make it easier to work with.

[
  {
    "name": "bill",
    "car": "jaguar",
    "age": 30,
    "profiles": [
      {
        "name": "stacey",
        "car": "lambo",
        "age": 23,
        "profiles": [
          {
            "name": "martin",
            "car": "lexus",
            "age": 34,
            "profiles": []
          }
        ]
      }
    ]
  }
]

This is the expected output.

[
  {
    "name": "bill",
    "car": "jaguar",
    "age": 30,
  },{
    "name": "stacey",
    "car": "lambo",
    "age": 23,
  },{
    "name": "martin",
    "car": "lexus",
    "age": 34,
  }
]

Each profiles array can have n amount of items, which may or may not have an empty array of sub profiles. Note the converted array objects don't contain profiles after the conversion.

I'm open to using underscore or lodash to achieve this.

like image 468
ThomasReggi Avatar asked Jul 31 '26 13:07

ThomasReggi


1 Answers

Let's call your original data o, combining Array.prototype.reduce with recursion I came up with this:

o.reduce(function recur(accumulator, curr) {
   var keys = Object.keys(curr);
   keys.splice(keys.indexOf('profiles'), 1);

   accumulator.push(keys.reduce(function (entry, key) {
       entry[key] = curr[key];
       return entry;
   }, {}));

   if (curr.profiles.length) {
       return accumulator.concat(curr.profiles.reduce(recur, []));
   }

   return accumulator;
}, []);
like image 128
axelduch Avatar answered Aug 02 '26 02:08

axelduch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!