Javascript - How To Create An Associative Array That Guarantees Order?
Solution 1:
In ECMAScript 6 Map type is an ordered list of key-value pairs, where both the key and the value can have any type. A Map object iterates its elements in insertion order.
The forEach
method executes a provided function once per each key/value pair in the Map object, in insertion order.
var a = newMap;
a.set("first", "first");
a.set("2", "2");
a.set("34", "34");
a.set("1", "1");
a.set("second", "second");
a.forEach(function(value, key) {
console.log(key + ' => ' + value)
})
You can also use for...of
loop and it returns an array of [key, value]
for each iteration.
var a = newMap;
a.set("first", "first");
a.set("2", "2");
a.set("34", "34");
a.set("1", "1");
a.set("second", "second");
for (var p of a) console.log(p)
Solution 2:
You cannot save properties in a specific order in object, but you can parse it while printing in any custom order. You will have to create another array of values or if to be printed on document, then an HTML string.
You can try something like this:
Note: You can check using comparison operator >
or <
. You can parse numeric values and compare or string compare non-numeric values, but will give issues if you have something like eleven
.
var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second"
};
var sortOrder = ["1", "2", "34", "first", "second"];
var html = Object.keys(obj).sort(function(a,b){
var _a = getSortPosition(a);
var _b = getSortPosition(b);
return _a> _b ? 1: _a<_b ? -1 : 0;
}).map(function(item){
return"<span>" +item+ "</span>";
}).join("<br/>");
document.getElementById("content").innerHTML = html;
functiongetSortPosition(key){
var _index = sortOrder.indexOf(key);
return _index >-1 ? _index : 999;
}
<divid="content"></div>
Post a Comment for "Javascript - How To Create An Associative Array That Guarantees Order?"