The json object is
var data = [{"Parent":1,"Child":[4,5,6]},{"Parent":2},{"Parent":3}]
How can I use underscore.js chain/map/pluck etc... function to get the flatten result
var result = [];
for (var i = 0; i < data.length; i++) {
result.push(data[i].Parent);
if (data.Child != undefined) {
for (var j = 0; j < data[i].Child.length; j++) {
result.push(data[i].Child[j]);
}
}
}
console.log(result) >> //1,4,5,6,2,3
Alternatively, if you want a function that can universally flatten any collection of objects or arrays,
You could extend Underscore with:
Crush (for lack of a better name) can be called like
_.crush(list, [shallow])
or_(list).crush([shallow])
and behaves exactly like a generalized form of Underscore's built-in Flatten.It can be passed a collection of nested objects, arrays, or both of any depth and will return a single-leveled array containing all of the input's values and own properties. Like Flatten, if it is passed an additional argument which evaluates to true, a "shallow" execution is performed with the output only flattened one level.
Example 1:
Example 2:
An explanation of the code itself is as follows:
Hope it helps if anyone needs it. :)
If you want to use underScore.js to flatten an array of many arrays into one array of elements, that's how you do it. Follow my example:
My graph has 2 series. Each series has a name and a sequence of datapoints {xtime, yValue}. My goal is to iron out all the data points from 2 series into one series of data points so to fill out a table.
My result :
Assuming you want to first get the parents and then get the children:
Here's a shorter solution: