I need to flatten a nested object. Need a one liner. Not sure what the correct term for this process is. I can use pure Javascript or libraries, I particularly like underscore.
I've got ...
{
a:2,
b: {
c:3
}
}
And I want ...
{
a:2,
c:3
}
I've tried ...
var obj = {"fred":2,"jill":4,"obby":{"john":5}};
var resultObj = _.pick(obj, "fred")
alert(JSON.stringify(resultObj));
Which works but I also need this to work ...
var obj = {"fred":2,"jill":4,"obby":{"john":5}};
var resultObj = _.pick(obj, "john")
alert(JSON.stringify(resultObj));
This is a function I've got in my common libraries for exactly this purpose. I believe I got this from a similar stackoverflow question, but cannot remember which (edit: Fastest way to flatten / un-flatten nested JSON objects - Thanks Yoshi!)
This can then be called as follows:
You can also append this function to the standard Javascript string class as follows:
With which, you can do the following:
Here you go:
Summary: 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.For those who don't care about the one-line craziness and would prefer to be able to actually read it (depending on your definition of readability):
Here are vanilla solutions that work for arrays, primitives, regular expressions, functions, any number of nested object levels, and just about everything else I could throw at them. The first overwrites property values in the manner that you would expect from
Object.assign
.The second accumulates values into an array.
Also please do not include code like this in production as it is terribly difficult to debug.
It's not quite a one liner, but here's a solution that doesn't require anything from ES6. It uses underscore's
extend
method, which could be swapped out for jQuery's.Simplified readable example, no dependencies
Working example: https://jsfiddle.net/webbertakken/jn613d8p/2/
Here goes, not thoroughly tested. Utilizes ES6 syntax too!!