Reputation: 386
How can I remove an element using its position of an object? I for example want to remove the second one.
Object {duur: ".short", taal: ".nl", topic: ".algemeen-management"}
Upvotes: 0
Views: 21000
Reputation: 428
like this :
var index = 1 ; // the position you want minus 1
var example = {duur: ".short", taal: ".nl", topic: ".algemeen-management"}
delete example[Object.keys(example)[index]];
Upvotes: 2
Reputation: 167162
The Object.keys()
will give you in the order of how it is defined. Always it is better to remove based on the key name. Because, in an object, the keys are not exactly sorted and they don't have any order.
var obj = {
duur: ".short",
taal: ".nl",
topic: ".algemeen-management"
};
console.log(obj);
var position = 2;
delete obj[Object.keys(obj)[position - 1]];
console.log(obj);
The best and right way to do is to remove by the key name:
var obj = {
duur: ".short",
taal: ".nl",
topic: ".algemeen-management"
};
console.log(obj);
var key = "taal";
delete obj[key];
console.log(obj);
Upvotes: 5