I know how to change the value of a object but is it possible to change the name of a key or change the index position of a key?
const object1 = {
"a": 'helloa',
"b": 'hellob',
"c": 'helloc',
"d": 'hellod'
};
console.log(object1.b);
// hellob
What I want:
// "a": 'helloa'
// "c": 'helloc'
// "b": 'hellob'
// "d": 'hellod'
Solution:
Help from @line-o
The solution is to put all values in an object and then change the order of the array. A sorting algorithm then changes the values of the object with the values of the array.
var object1 = { "a": "1", "b": "2", "c": "3", "d": "4", "e": "5" }
const order = ["a", "b", "c", "x", "d", "e"];
// add new item in list
object1["x"] = "6" ;
// Change order of items
var a = order.indexOf("a");
var e = order.indexOf("e");
if (~a) {
order[a] = "e";
}
if (~e) {
order[e] = "a";
}
const sorted = Object
.keys(object1)
.sort(function (a, b) {
/* my sorting algo */
const indexA = order.indexOf(a)
const indexB = order.indexOf(b)
return indexA - indexB;
});
object1 = order.map(key => object1[key]);
console.log(object1);