javascript - Moving a deep-set member of a multidimensional array tree - using lodash or underscore -
i want move deep set member of tree using lodash or equivalent code.
example tree
[ { id: 32, name: 'unique name', children: [] }, { id: 43, name: 'unique name', children: [] }, { id: 55, name: 'unique name', children: [ { id: 31, name: 'unique name', children: [] }, { id: 63, name: 'unique name', children: [] }, { id: 84, name: 'unique name', children: [ { id: 47, name: 'unique name', children: [] }, { id: 56, name: 'unique name', children: [] } ] } ] } { id: 67, name: 'unique name', children: [ { id: 78, name: 'unique name', children: [] }, { id: 89, name: 'unique name', children: [] }, ] }, { id: 30, name: 'unique name', children: [] } ]
how can i:
- locate specific object id: 47
- move object (with id: 47) new level of tree
would preferably use lodash. tree can of infinite depth.
edit in response chosen answer re-worked code more accurately fit question description: https://jsfiddle.net/j88vencp/4/
if can change structure of tree must easier operate on in way want:
var collection = { 32 : { id: 32, name: 'unique name', children: {} }, 43: { id: 43, name: 'unique name', children: {} }, 55: { id: 55, name: 'unique name', children: { 31: { id: 31, name: 'unique name', children: {} }, 63: { id: 63, name: 'unique name', children: {} }, 84: { id: 84, name: 'unique name', children: { 47: { id: 47, name: 'unique name', children: {} }, 56: { id: 56, name: 'unique name', children: {} }, } }, } } } function moveelement(el, obj) { var newel = el; var id = el.id; // removing , moving stuff here console.log(newel); // remove collection _.omit(obj, el.id); // add collection in upper tree obj[id] = newel; console.log(obj); } function deepsearch(obj, origobj, val) { (var key in obj) { if (obj.hasownproperty(key)) { var el = obj[key]; if (_.size(el.children) > 0) { deepsearch(el.children, origobj, val); } if (key == val) { moveelement(el, origobj); return; } } } } deepsearch(collection, collection, 56);
here fiddle --> https://jsfiddle.net/j88vencp/4/
Comments
Post a Comment