massivelines
7/12/2018 - 9:41 PM

Flatten nested objects

const nested = {
  id: 1,
  children: [
    { id: 2 },
    { id: 3,
      children: [{ id: 5 }, { id: 6 }]
    },
    { id: 4 }
  ]
}

const flatten = function(obj) {
  const array = Array.isArray(obj) ? obj : [obj];
  return array.reduce(function(acc, value) {
    acc.push(value);
    if (value.children) {
      acc = acc.concat(flatten(value.children));
      delete value.children;
    }
    return acc;
  }, []);
}

flatten(nested);
// => [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 5 }, { id: 6 }, { id: 4 } ]