0

I've been tinkering and was looking at for loops etc, then thought there's probably a quicker way to do this. Then I got lost in the lodash docs...

Anyway, I want to run over the following object—

{ stuff: { thing1: 'value1', thing2: 'value2', thing3: 'value3' }, something: 'value4' } 

—and return:

{ thing1: 'value1', thing2: 'value2', thing3: 'value3', something: 'value4' } 

That is, I want to eliminate the stuff level and have everything as siblings. In an easy / terse way, I mean. I tried _.flatten and ._flattenDepth but they only work with arrays (returns an empty array).

Thanks

1 Answer 1

1

I think your best/only bet is a loop.

function flattenObject(obj, res) { res = res ? res : {}; Object.keys(obj).forEach(function(d) { if (typeof obj[d] === 'object') return flattenObject(obj[d], res); res[d] = obj[d]; }); return res; } console.log(flattenObject(a)); 
Sign up to request clarification or add additional context in comments.

2 Comments

res is the resulting object. In the function's first line I'm just checking if res is passed (already an object), and if not, I create a new empty one. @heydon
Oh, okay. My reading! I missed that res was in the return line.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.