I am trying to custom sort a JavaScript object but not able to get how we can do this in a right way. Say I am having an object like
var test = {
\'yellow\
JavaScript objects are hashes and therefore inherently un-ordered. You cannot make an object with properties in any given order. If you are receiving an ordering when you enumerate the keys, it is purely coincidental, or better said, an implementation detail of the JavaScript engine.
You'd have to use an array of objects to achieve something like what you want to do.
In other words, it is not possible with the data structure you have chosen.
May be you could change this using JSON.stringify()
do like
var json = { "name": "David", "age" : 78, "NoOfVisits" : 4 };
console.log(json);
//outputs - Object {name: "David", age: 78, NoOfVisits: 4}
//change order to NoOfVisits,age,name
var k = JSON.parse(JSON.stringify( json, ["NoOfVisits","age","name"] , 4));
console.log(k);
//outputs - Object {NoOfVisits: 4, age: 78, name: "David"}
put the key order you want in an array and supply to the function. then parse the result back to json.
You could use Map()
A Map object iterates its elements in insertion order
var arr = ['red', 'green', 'blue', 'yellow'];
var map = new Map();
arr.forEach(function(val, index) {
var obj = {};
obj[val] = [];
map.set(index, obj)
});
console.log(map)