jeudi 1 janvier 2015

moving or splicing elements within nested JavaScript objects with string key


I have a nested object I want to manipulate in javascript, splicing an element (and all its children) from one position and placing it in another using location strings to determine the removal and insertion point. I found an question that has several good answer on how access a nested object using a string:


Accessing nested JavaScript objects with string key


(working example : http://ift.tt/1ybxwXk)


but I have no idea how I can adapt this to allow splicing an element from one positions in the object to another. e.g.



var from = "part1";
var to = "part3[0]


This would remove element at from (someObject["part1"] and re-insert it at to someObject["part3][0]


so if my object looks like this:



var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}, {
'name': 'Part 3B',
'size': '5',
'qty' : '20'
}, {
'name': 'Part 3C',
'size': '7.5',
'qty' : '20'
}
]
};


after the slice I would get



var someObject = {
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
},
{
'name': 'Part 3B',
'size': '5',
'qty' : '20'
}, {
'name': 'Part 3C',
'size': '7.5',
'qty' : '20'
}
]
};




Aucun commentaire:

Enregistrer un commentaire