How can we custom sort JavaScript object keys?

烈酒焚心 提交于 2019-12-02 07:44:43

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.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!