I want to add a value at first number of an object, but its not adding at first number, How can I do this?
let obj = {'b': 2, 'c': 3, '3': 33, '4': 44};
const addNewValue = Object.assign({a: 1}, obj);
console.log(addNewValue);
Output should be as given below:-
{
"a": 1,
"3": 33,
"4": 44,
"b": 2,
"c": 3
}
But getting as given below:-
{
"3": 33,
"4": 44,
"a": 1,
"b": 2,
"c": 3
}
Thanks for your efforts!
2
Answers
As you can see below you cannot retain the order because you have numeric key mixed into this.
If the keys started with alphabetics you could since ES6 rely on order if you keep the traversal order
The code below shows how the order is already wrong as soon as we try to get the keys in any way
I posted this as dupe, but it was not. It does however explain why your object is not able to keep the order you gave it
Sort a JavaScript object by key or value; ES6
A JS object doesn’t retain property insertion order with numbers, but
Map
does.You could use a proxy to emulate an object-like map: