Reputation: 9447
I have following type of data
data = [{
"grp" : ["A", "B", "C"],
"val" : [1, 2, 3]
}, {
"grp" : ["A", "B", "D"],
"val" : [2, 3, 4]
}, {
"grp" : ["A", "C", "C"],
"val" : [1, 3, 5]
}, {
"grp" : ["B", "Y", "E"],
"val" : [1, 3, 2]
}
]
I want to make groups like these
groups = {
"A": {
"B": {
"C": [
[1, 2, 3],
[2, 3, 4]
],
"D": [
[1, 2, 3],
[2, 3, 4]
]
},
"C": {
"C": [
[1, 3, 5]
]
}
},
"B": {
"Y": {
"E": [
[1, 3, 2]
]
}
}
}
grp
array can be have maximum of 3 elements.
I tried using underscorejs something like below, however, I ended up creating individual groups, not nested groups.
var groups = _(data).reduce(function(memo, o) {
_(o.groups).each(function(j) {
memo[j] = memo[j] || [ ];
memo[j].push(o);
});
return memo;
}, { });
Would appreciate any idea in the right direction.
Upvotes: 1
Views: 1174
Reputation: 3813
Try this:
var data = [{
"grp": ["A", "B"],
"val": [1, 2, 3]
}, {
"grp": ["A", "B"],
"val": [2, 3, 4]
}, {
"grp": ["A", "C"],
"val": [1, 3, 5]
}, {
"grp": ["B", "Y"],
"val": [1, 3, 2]
}]
// create an object to hold the revised structured data
var newData = {};
_.map(data, function (obj, key) {
// check whether object is present or not
if (_.isUndefined(newData[obj.grp[0]])) { //if object is undefined
newData[obj.grp[0]] = {};
newData[obj.grp[0]][obj.grp[1]] = [obj.val]; // add an array to second child of grp
} else { // if object already exists
// check whether second child of grp is present
if (_.isUndefined(newData[obj.grp[0]][obj.grp[1]])) { // if not present - create an associated array
newData[obj.grp[0]][obj.grp[1]] = [obj.val];
} else { // if present - add value to it
newData[obj.grp[0]][obj.grp[1]].push(obj.val);
}
}
});
// print on console window
console.log(newData);
JSFiddle link: http://jsfiddle.net/4G57E/
Upvotes: 1
Reputation: 43235
var out = {};
_.each(data,function(item)
{
var firstKey = item['grp'][0];
var secondKey = item['grp'][1];
out[firstKey] = out[firstKey] || {};
out[firstKey][secondKey] = out[firstKey][secondKey] || [];
out[firstKey][secondKey].push(item['val']);
});
demo:http://jsfiddle.net/HJngC/2/
Upvotes: 0