2

I have a list like this one (it is already proper sorted in php)

myList = {  
   "394":"Andres",
   "388":"Franck",
   "380":"John",
   "415":"Philip"
}

But if I use data = JSON.parse(myList) to make an object for dropdown, as respons I am getting list automatically sorted by keys what actually I do not want.

Result:

data = {
   "380":"John",
   "388":"Franck",
   "394":"Andres",
   "415":"Philip"
}

So what is the best way to make sort on list as JSON object to get list sorted by values?

I have tried:

var keyList = Object.keys(data).sort(function(a,b){return data[a]-data[b]});
   var valueLIst = Object.values(data).sort(function(a,b){return data[a]-data[b]});

   var obj = {};
   for(var i=0,len=keyList.length; i < len ;i++) {
     obj[keyList[i]] = valueLIst[i];
   }
1
  • 1
    The order of keys in objects is not guaranteed. Do not rely on it. Use array instead. Commented Aug 2, 2017 at 9:11

1 Answer 1

2

Ideally your PHP API should be returning an array, because JavaScript objects are an unordered collection of properties by definition.

4.3.3 Object

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

However, you could transform the API response into an ordered array of objects, if you want to keep the PHP response how it is now:

Object.keys(data).map(key => ({ id: key, value: data[key] }))
                 .sort((a, b) => a.value.localeCompare(b.value));

Interestingly you could also use Map which orders based on insertion order.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.