Last active
December 24, 2015 21:19
-
-
Save sideshowcoder/6864739 to your computer and use it in GitHub Desktop.
unflatten an array of objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var _ = require("underscore") | |
var res = [] | |
var arr = [ | |
{'id':21 ,'name' : 'name1' ,'vehiclename' : 'vehicle1' ,'parentid' : 21}, | |
{'id':21 ,'name' : 'name1' ,'vehiclename' : 'vehicle2' ,'parentid' : 21}, | |
{'id':22 ,'name' : 'name2' ,'vehiclename' : 'vehicle1' ,'parentid' : 22}, | |
{'id':22 ,'name' : 'name2' ,'vehiclename' : 'vehicle2' ,'parentid' : 22}, | |
] | |
var connected = [{ | |
name: "vehicles", | |
props: [ "vehiclename", "parentid" ] | |
}] | |
arr.forEach(function(e) { | |
var obj = _.findWhere(res, { id: e.id }) | |
if(!obj) { | |
obj = { id: e.id } | |
res.push(obj) | |
} | |
var props = _.omit(e, "id"); | |
connected.forEach(function(cp) { | |
props = _.omit.apply(this, [props, cp.props]) | |
}) | |
for(p in props) { | |
copyPropToObj(props[p], p, obj); | |
} | |
connected.forEach(function(cp) { | |
copyPropToObj(_.pick.apply(this, [e, cp.props]), cp.name, obj) | |
}) | |
}) | |
function copyPropToObj(prop, propName, obj) { | |
var oProp = _.clone(obj[propName]) | |
if(oProp && (prop === oProp)) { | |
return | |
} else if(oProp) { | |
// we already have a value, need to move to an array | |
obj[propName] = [] | |
obj[propName].push(prop) | |
obj[propName].push(oProp) | |
} else { | |
// we don't have it set yet so just copy over | |
obj[propName] = prop | |
} | |
} | |
res.forEach(function(e) { | |
console.log(e) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment