user3071261
user3071261

Reputation: 386

Remove element from object jquery

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

Answers (4)

Developer
Developer

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

Dion Zac
Dion Zac

Reputation: 69

You can siply use : delete(object.taal).

Upvotes: 0

avilac
avilac

Reputation: 802

Better use the delete operator like this:

delete myObject.taal;

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

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

Related Questions