'How to remove the first property of an object?
How do I remove the first property of an object like:
var obj = { x:1, y:2, z:3 };
so that obj
becomes:
{ y:2 , z:3 };
This approach doesn’t work for me:
delete obj.x
as I don't know any details about the object’s properties.
I just need to delete the first property.
Solution 1:[1]
First of all: Javascript (ES5) don't guarantee property order. There are still browsers running on ES5 (IE11 ahem, although they keep property order partially) so depending on your environment, I recommend you to follow this rule.
That's a really really important point.
Now, after you understood why you shouldn't do that, I'll explain a way to remove the first property (whatever first is in your current environment).
You can do it two ways. The most performant way in IE11 and Firefox is this one:
for (var i in obj) {
delete obj[i];
break;
}
And also you can do:
delete obj[Object.keys(obj)[0]];
Which is less performant on IE and Firefox but better on Chrome (performance test below):
function newList() {
var objs = [];
var props = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ";
for (var i = 0; i < 200000; i++) {
var obj = {};
for (var ii = 0; ii < props.length; ii++) {
obj[props[ii]] = ii;
}
objs.push(obj);
}
return objs;
}
var objs = newList();
console.time("Object.keys()");
for (var i = 0; i < objs.length; i++) {
delete objs[i][Object.keys(objs[i])[0]];
}
console.timeEnd("Object.keys()");
objs = newList();
console.time("for...in");
for (i = 0; i < objs.length; i++) {
for (var j in objs[i]) {
delete objs[i][j];
break;
}
}
console.timeEnd("for...in");
NOTE: Woah, surprise for me. In V8 Object.keys() works pretty well right now. But in Firefox and IE11 preformance is still worse.
Not tested more browsers as those 3 are the only ones I develop for (yeah... IE11...). Surprised also that IE11 has better performance than Firefox. Usually is way worse.
Seems that the overhead for Object.keys()
is when creating the array, but the overall performance changes with the amount of properties on both ways. Thank you for telling me to do some tests Jonas Wilms.
Solution 2:[2]
In modern JS environments (ES2015+), the ordering of keys is well-defined so you should be able to do something like this:
const keys = Reflect.ownKeys(obj); // thanks to Paulpro for improving this!
if (keys.length) delete obj[keys[0]];
Note that delete
won't always work, but for most "normal" objects this should do what you need.
Since there's some contention over the ordering of JS objects, here's the ECMAScript standard: https://www.ecma-international.org/ecma-262/6.0/#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |