最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

jquery - How to remove a part of an object in javascript - Stack Overflow

matteradmin1PV0评论

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

Share Improve this question edited Feb 20, 2012 at 10:48 gideon 19.5k11 gold badges74 silver badges114 bronze badges asked Feb 20, 2012 at 10:41 Ali ForoughiAli Foroughi 4,6297 gold badges44 silver badges67 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

Just 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.

Post a comment

comment list (0)

  1. No comments so far