3

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

gideon
  • 19,329
  • 11
  • 72
  • 113
Ali Foroughi
  • 4,540
  • 7
  • 42
  • 66

4 Answers4

8

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

That's about it

Jibi Abraham
  • 4,636
  • 2
  • 31
  • 60
1
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.

ldgorman
  • 1,553
  • 1
  • 14
  • 39
1

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;
    }
}
Rob W
  • 341,306
  • 83
  • 791
  • 678
MyStream
  • 2,533
  • 1
  • 16
  • 33
0

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.

Ash Clarke
  • 4,807
  • 1
  • 37
  • 48