3
votes

This is my code :

var data = [];
$("#btn").click(function(){
    total++;
    data.push({        
        id : total,
        "cell": [
            "val1",
            "val2",
            "val3",
        ]
    });
});

Every time that user clicks on btn button, I add some values to the data object. Now my question is here that how I can remove the part that has id = X

4

4 Answers

1
votes

You can use .splice() at position X

var data = [{id : total, "cell" : ["val1", "val2", "val3"]}[, ...repeat];

var X = 0; // position to remove
data.splice(X,1);

extension:

for (var i=data.length-1; 0 < i; i--) {
    if (data[i].id == X) {
        data.splice(X,1);
        break;
    }
}
8
votes

Just use
x = {id1: "some value"}
delete x.id1

That's about it

1
votes
const {  whatIDontWant, ...theRest } = everything;
return {theRest};

Let the LHS equal the RHS, whatIDontWant is excluded from theRest because of uniqueness of properties within an object evaluated when spreading. Therefore theRest is an object without the unwanted property.

0
votes

Here's an alternative idea. Using the id as a key in an object instead:

var data = {};

$("#btn").click(function(){
    total++;
    data[total] = {
        cell: [
            "val1",
            "val2",
            "val3"
        ]
    };
});

Then to delete the object that has that specific id you can do:

delete data[id];

or

data[id] = null;

to just null it.

This way you remove the complexity from having an array there too.