javascript - re order key/values in object based on values in array -


this question has answer here:

just found

sort javascript object key

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

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -