Remove JSON element with index?

Viewed 1621

So let's say I have a JSON called foo:

{
     "key" : "value",
     "one" : "two"
}

I want to delete the first element, so with the index of 0. But I don't know that it's key.

I tried using delete foo[0] but it didn't work. It outputs true but it doesn't actually delete it.

Is there a way to do this without looping through it?

4 Answers

Get the key with Object.keys(JSON)[0] and then remove it.

JSON object properties have no order like arrays. However, you can get the list of properties with:

Object.keys(foo);  // ["key","one"]

and remove the first element found using delete.

delete foo[ Object.keys(foo)[0] ]

In some browsers, as I see, the order is determined by which property was created first, but this is not guaranteed and you can't rely on that. So, you may be deleting any property if the order logic is different.

The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified. Properties of the object being enumerated may be deleted during enumeration. If a property that has not yet been visited during enumeration is deleted, then it will not be visited. If new properties are added to the object being enumerated during enumeration, the newly added properties are not guaranteed to be visited in the active enumeration. A property name must not be visited more than once in any enumeration. https://www.ecma-international.org/ecma-262/5.1/#sec-12.6.4

You can use Object.keys to get a list of the objects keys. This is in general not a good idea, so maybe think if theres a better way, but here is the code for what you are trying to do:

test = {
     "key" : "value",
     "one" : "two"
}

delete test[Object.keys(test)[0]]

The object is not an array and therefore element of object cannot be deleted by index. However, you can get an array of object keys.

Object.keys(foo)

Now we have the array and can get a key by index. Also, we can delete an element by getting the key by index.

delete foo[Object.keys(foo)[index]];

It's convenient to write a prototype so that the сode don't turn out to be cumbersome.

Object.prototype.deleteByIndex = function(index) {
    delete this[Object.keys(this)[index]];
};

let foo = {
    "one": "test 1",
    "two": "test 2"
}

foo.deleteByIndex(0);
Related