javascript - Better Solution for Unflattening Array of Objects -
for following array of objects
[ {"corp": "abc", "t1": "hw a/v", "t2": "a/v system","t3": "audio","prod": "audio system","mfr": "one"}, {"corp": "abc", "t1": "hw a/v", "t2": "a/v system","t3": "audio","prod": "audio system","mfr": "two"}, {"corp": "abc", "t1": "hw a/v", "t2": "a/v system","t3": "video","prod": "video system","mfr": "other"} ]
i intend unflatten object 1 below :
[{ "corp": "abc", "list": [{ "t1": "hw a/v", "list": [{ "t2": "a/v system", "list": [{ "t3": "audio", "list": [{ "prod": "audio system", "list": [ {"mfr": "one"}, {"mfr": "two"} ] }] }, { "t3": "video", "list": [{ "prod": "video system", "list": [ {"mfr": "other"} ] }] }] }] }]
}] did result intend described above. used underscore result. following code snippet did job me :
var items = _.map(_.groupby(itemlist, 'corp'), function (a) { return _.extend(_.pick(a[0], 'corp'), { list: _.map(_.groupby(a, 't1'), function (b) { return _.extend(_.pick(b[0], 't1'), { list: _.map(_.groupby(b, 't2'), function (c) { return _.extend(_.pick(c[0], 't2'), { list: _.map(_.groupby(c, 't3'), function (d) { return _.extend(_.pick(d[0], 't3'), { list: _.map(_.groupby(d, 'prod'), function (e) { return _.extend(_.pick(e[0], 'prod'), { list: _.map(e, function (elem) { return _.pick(elem, 'mfr') }) }); }) }); }) }); }) }); }) }); });
now, looking for, if can enhance solution. want optimize both space , time process.
ps: in morning, had asked similar question requesting solution, , question marked as too broad , put on hold, so have added solution question, looking better solution.
thanks
in order avoid imbricated statements, may want define list of 'expand keys' , iterate on them.
it's half-tempting automatically extract keys like:
expandkeys = _.keys(itemlist[0]);
but since javascript doesn't guarantee order of keys in object, should define list explicitly instead.
below example code.
var itemlist = [ {"corp": "abc", "t1": "hw a/v", "t2": "a/v system", "t3": "audio", "prod": "audio system", "mfr": "one"}, {"corp": "abc", "t1": "hw a/v", "t2": "a/v system", "t3": "audio", "prod": "audio system", "mfr": "two"}, {"corp": "abc", "t1": "hw a/v", "t2": "a/v system", "t3": "video", "prod": "video system", "mfr": "other"} ]; var expandkeys = [ 'corp', 't1', 't2', 't3', 'prod', 'mfr' ]; function expandlist(list, keys) { var node, obj, root = {}; _.each(list, function(item) { obj = root; _.each(keys, function(key) { obj = (obj.list = obj.list || []); node = _.find(obj, function(i) { return i[key] == item[key]; }); if(node === undefined) { obj.push(node = {}); node[key] = item[key]; } obj = node; }); }); return root.list; } var res = expandlist(itemlist, expandkeys); console.log(res);
<script src="http://underscorejs.org/underscore-min.js"></script>
Comments
Post a Comment