DEV Community

Discussion on: Javascript: Convert nested JSON to simple JSON

Collapse
 
msabir profile image
imsabir

You can also use the spread operator for this:

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

Explanation:
Recursively create an array of one-property objects, then combine them all with Object.assign.

This uses ES6 features including Object.assign or the spread operator, but it should be easy enough to rewrite not to require them.

*Spread Operator: *
The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.

For more: @msabir

Collapse
 
urstrulyvishwak profile image
Kurapati Mahesh

That so cool. Thanks. Helpful to many :)