0

Says I have this saved key in my localstorage, how to remove the player_id that has value of 2 and shoe size_of 1?

[{"player_id":1,"shoe_size":3},{"player_id":2,"shoe_size":1},{"player_id":2,"shoe_size":2},

What to do next after I get the saved value?

if(localStorage["player"]){
    player = JSON.parse(localStorage["player"]);
}

1 Answer 1

1

You can use .filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

player  = player .filter(function( obj ) {
    return !(obj.player_id == 2 && obj.shoe_size == 1);
});

If you want to set it:

localStorage["player"] = JSON.stringify(player)

var player = [{"player_id":1,"shoe_size":3},{"player_id":2,"shoe_size":1},{"player_id":2,"shoe_size":2}];

player  = player.filter(function(obj) {
    return !(obj.player_id == 2 && obj.shoe_size == 1);
});

document.write(JSON.stringify(player))

Sign up to request clarification or add additional context in comments.

4 Comments

is filter a jquery function or pure js?
can it be this.player_id instead of obj.player_id?
yes,thanks so much! but can I it use map or grep? What's the advantage of using filter()?
@AaronMusktin Array.prototype.map() returns one element for every element in the original array. Array.prototype.filter() returns only the specific elements that return true in the function provided. They are used in different situations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.