javascript - UnderscoreJS - how to flatten a object using one of the iterator? -
i make breadcrumb. , getting data end this:
var object = { "department": { "deptcode": null, "description": "123", "deptname": { "name": "xyz" } }}
and using underscore or jquery modify object this:
var result = { "department.deptcode": null, "department.description": "123", "department.deptname.name": "xyz" }
i tried using undrscore, not result. 1 show me possible way done?
my try:
var lable = []; _.each(object, function(key, obj){ var title = obj; if(_.object(key)){ _.each(key, function(text,obj){ lable.push(title + '.' + obj + ':' + text); }) } }); console.log(lable);
try creating recursive function, (based on fiddle):
var lable = {}; function flatten(object, title) { _.each(object, function(key, obj){ var newtitle = obj; if (key != null && typeof(key)=='object') { flatten(key, (title) ? title + '.' + newtitle : newtitle); } else { lable[title + '.' + newtitle] = key; } }); }; flatten(object, ''); console.log(lable);
check fiddle: http://jsfiddle.net/aczs8/2/
another alternative, replacing global variable approach closures, define more reusable flatting function:
function flatten(mainobject) { var lable = {}; flattenaux = function(object, title) { _.each(object, function(key, obj){ var newtitle = obj; if (key != null && typeof(key)=='object') { flattenaux(key, (title) ? title + '.' + newtitle : newtitle); } else { lable[title + '.' + newtitle] = key; } }); }; flattenaux(mainobject, null); return lable; } var testresult = flatten(object); console.log(testresult);
example fiddle: http://jsfiddle.net/aczs8/6/
Comments
Post a Comment