0

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"}
user3071261
  • 356
  • 2
  • 7
  • 21
  • 1
    Properties are not ordered. You cannot reliably say which one is the "second" property. – Felix Kling Jan 05 '17 at 15:04
  • Possible duplicate of [How to remove a property from a JavaScript object?](http://stackoverflow.com/questions/208105/how-to-remove-a-property-from-a-javascript-object) – Jason Krs Jan 05 '17 at 15:04
  • object keys don't have a [guaranteed order](http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – maioman Jan 05 '17 at 15:05

4 Answers4

5

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);
Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226
  • 3
    It seems you are contradicting yourself. First you say `Object.keys()` returns the properties in the order they are defined, then you say keys don't have any order ;) To back up the second third sentence: `Object.keys({foo: 42, 21: 'x'})` (returns `[21, 'foo']` in Chrome, not `['foo', 21]`. – Felix Kling Jan 05 '17 at 15:06
  • @FelixKling Ah right. But, defined order is different... Well, eeks. I don't know how to put it correctly. – Praveen Kumar Purushothaman Jan 05 '17 at 15:06
  • 1
    I believe what @PraveenKumar is trying to say (and assuming the behavior is like Python) is that Object.keys() will return the keys in some order, but there's no way to know what that order will be (may or may not be the order objects were inserted), and you can't guarantee that the order won't change if you call it again later. – DaveTheScientist May 09 '18 at 19:12
2

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]];
Oriel.F
  • 390
  • 2
  • 17
0

Better use the delete operator like this:

delete myObject.taal;

avilac
  • 712
  • 1
  • 7
  • 23
0

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

Dion Zac
  • 69
  • 6