javascript - re order key/values in object based on values in array -
this question has answer here:
- sort javascript object key 22 answers
just found
i trying reorder key/values of object match values of array using underscore
input
{ 'red':'one', 'blue':'two', 'green':'three' }
array map to
['green','red','blue']
expected output
{ 'green':'three', 'red':'one', 'blue':'two' }
js objects have no inherent order ( does javascript guarantee object property order? ).
what can though, use array "apply" order . . . create array entries matches keys in object (as appear have) , then, when loop through array, reference key in object matches current value in array.
for (var = 0; < thearray.length; i++) { if (theobject.hasownproperty(thearray[i]) { . . . stuff theobject[thearray[i]] . . . } }
alternately, go array of objects, give values inherent order, have impacts on relationship of data in original object, how access data.
[ {'green':'three'}, {'red':'one'}, {'blue':'two'} ]
Comments
Post a Comment