object flatten js 1

object flatten js

Object.assign(
  {}, 
  ...function _flatten(o) { 
    return [].concat(...Object.keys(o)
      .map(k => 
        typeof o[k] === 'object' ?
          _flatten(o[k]) : 
          ({[k]: o[k]})
      )
    );
  }(yourObject)
)

Here is what the above code is Doing:
1. We’re using the spread operator to convert the array returned by _flatten() into an object.
2. _flatten() is a recursive function that takes an object as an argument.
3. We’re using the spread operator to convert the array returned by map() into an array of objects.
4. If the value of the current key is an object, we’re recursively calling _flatten() on it.
5. If the value of the current key is not an object, we’re returning an object with the key and its value.
6. We’re using the spread operator to convert the array returned by concat() into an array of objects.
7. We’re using the spread operator to convert the array returned by Object.keys() into an array of keys.
8. We’re using the spread operator to convert the array returned by map() into an array of objects.
9. We’re using the spread operator to convert the array returned by concat() into an array of objects.
10. We’re using the spread operator to convert the array returned by Object.keys() into an array of keys.

Similar Posts