Easy Tutorial
❮ Awk User Defined Functions Merge Sort ❯

Thoroughly Deleting Elements in an Array of JSON Objects in JS

Category Programming Techniques

In JS, for an array composed of JSON objects, such as:

var test = [{ "a": "1", "b": "2" }, { "a": "3", "b": "4" }, { "a": "5", "b": "6" }];

If we want to delete the second JSON object, how should we do it? In fact, the method is exactly the same as operating on an array.

Initially, I tried using the delete operator, but when I checked the array length, I found that this method does not actually delete the element thoroughly; it deletes its value but still retains the space.

var test = [{ "a": "1", "b": "2" }, { "a": "3", "b": "4" }, { "a": "5", "b": "6" }];
test.length   //Outputs 3
delete test[1];
test.length   //Still outputs 3

We know that the delete operator only sets the value to undefined and does not affect the array length, thus turning it into a sparse array (Section 7.5 of "JavaScript: The Definitive Guide").

Understanding this, one might think of moving each element after the deletion point one unit forward to completely remove the element, but in JS methods, we can find a more convenient way: the splice() method

var test = [{ "a": "1", "b": "2" }, { "a": "3", "b": "4" }, { "a": "5", "b": "6" }];
test.length   //Outputs 3
test.splice(1, 1);
test.length   //Outputs 2

After the deletion, test.length becomes 2, which is exactly the result we want.

>

Original article link: https://blog.csdn.net/WI_232995/article/details/77776433

** Click to Share Notes

Cancel

-

-

-

❮ Awk User Defined Functions Merge Sort ❯