For example
let obj = {1:"asd",2:"sad"};
obj[-1] = "g"
the object will be
{1:"asd",2:"sad",-1:"g"},
I need that -1 key be from the beginning
For example
let obj = {1:"asd",2:"sad"};
obj[-1] = "g"
the object will be
{1:"asd",2:"sad",-1:"g"},
I need that -1 key be from the beginning
I don't think it is wise to use objects as arrays.
Anyway, -1
is not a valid index keys, that is why it is not sorted as the other integer property names. And you cannot really rely on property order.
What you can do is sort your values by key when you need it:
let obj = {1:"asd",2:"sad"};
obj[-1] = "g"
Object.keys(obj).sort((a,b) => a - b).forEach(key => console.log(key + ' => ' + obj[key]));
Javascript doesn't behave that way by default. There's a good article here explaining how it does behave.
Javascript property ordering is always chronological unless the property is a positive integer which makes it an array index, and they come first and are ordered. -1 isn't a positive integer. It's a string, so it comes in the order it was added. There's a snippet (below) that confirms the behaviour you're reporting.
let obj = {};
obj["ccccc"]="ccccc";
obj["bbbbb"]="bbbbb";
obj["aaaaa"]="aaaaa";
obj[10]=10;
obj[5]=5;
obj["-2"]=-2;
obj["-3"]=-3;
obj[-22]=22;
obj[0]=0;
console.log(Reflect.ownKeys(obj));
Object.keys(obj).sort().forEach(key => console.log(key))
There are a number of ways to implement the behavior you want, but you won't get it without coding. The easiest way to do that is to simply sort the keys using Object.keys(obj).sort()
, but as you can see from the example, by default, does a lexical sort that doesn't really work for numbers. You'd want to then improve that with sort((a,b) => a - b)
, but that's problematic if you need integers and strings as keys.