Data:
var data = [
{
\"id\": 1,
\"level\": \"1\",
\"text\": \"Sammy\",
\"type\": \"Item\",
\"items\": [
Here is my version of the recursive flattenItems function. Note that I have removed the items property at all levels in the final result.
function flattenItems(data) {
// flat is the array that we will return by the end
var flat = [];
data.forEach(function(item) {
// get child properties only
var flatItem = {};
Object.keys(item).forEach(function(key) {
if(item[key] && item.hasOwnProperty(key) && !Array.isArray(item[key])) {
flatItem[key] = item[key];
}
// recursive flattern on subitems
// add recursive call results to the
// current stack version of "flat", by merging arrays
else if(Array.isArray(item[key])) {
Array.prototype.push.apply(flat, flattenItems(item[key]));
}
});
flat.push(flatItem);
});
// sort by level before returning
return flat.sort(function(i1, i2) {
return parseInt(i1.level) - parseInt(i2.level);
});
}
Here is a fiddle using your sample data, check the console.