I have a function which deletes from an object array but when i check it's .length
its the same..
This is what i have:
console.log(data.length);
delete(data[i]);
console.log(data.length);
console.log(data);
My outputs end up like this:
3
3
[object Array]
I have attatched the image of the object array below, you see only 2 entires but the length is still 3.
The initial data im testing with is this:
[
{"equip":"0","name":"Test","id":"10"},
{"equip":"0","name":"Test","id":"4"},
{"equip":"0","name":"Test","id":"5"}
]
You can see my browser has deleted one from the object array.. so why does it still count 3, and how do I fix that so it counts correctly?
I have a function which deletes from an object array but when i check it's .length
its the same..
This is what i have:
console.log(data.length);
delete(data[i]);
console.log(data.length);
console.log(data);
My outputs end up like this:
3
3
[object Array]
I have attatched the image of the object array below, you see only 2 entires but the length is still 3.
The initial data im testing with is this:
[
{"equip":"0","name":"Test","id":"10"},
{"equip":"0","name":"Test","id":"4"},
{"equip":"0","name":"Test","id":"5"}
]
You can see my browser has deleted one from the object array.. so why does it still count 3, and how do I fix that so it counts correctly?
Share Improve this question asked Dec 27, 2013 at 4:29 SirSir 8,27717 gold badges88 silver badges154 bronze badges3 Answers
Reset to default 7The delete operator deletes a property from an object. In your case, property i
. Properties in an array are actually indexes 0
through array.length - 1
. Use splice instead:
data.splice(i, 1);
To find out the number of properties in an object, use Object.keys
:
Object.keys(data).length
will result in 2
When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Operators/delete
delete
is used to remove element from object for array use splice
array.splice(index, 1);