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
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 Answers
Reset to default 8Just use
x = {id1: "some value"}
delete x.id1
That's about it
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;
}
}
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.
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 plexity from having an array there too.