flatten nested objects with lodash or es6 javascript

You can grab the values of your object using Object.values(), and then use Object.assign() with the spread syntax to merge all the objects together:

const obj = { foo: { fruit: "watermelon", vege: "celery", }, bar: { fruit: "banana", candy: "snickers", drink: "coke", } };

const res = Object.assign({}, ...Object.values(obj));
console.log(res);

With lodash you can use the corresponding methods _.assign() and _.values():

const obj = { foo: { fruit: "watermelon", vege: "celery", }, bar: { fruit: "banana", candy: "snickers", drink: "coke", } };

const res = _.assign({}, ..._.values(obj));
console.log(res);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Both of these methods rely on the iteration order that Object.values() and for...in uses. In the latest spec this is something which can be relied on, but this hasn’t always been the case. If you need to read the values in a guaranteed order 100% of the time, you can consider specifying the order of keys using an array:

const obj = { foo: { fruit: "watermelon", vege: "celery", }, bar: { fruit: "banana", candy: "snickers", drink: "coke", } };

const order = ["foo", "bar"]; // visit foo first then bar
const res = Object.assign({}, ...order.map(k => obj[k]));
console.log(res);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top