1

I have an cart array into which I am pushing the elements like:

 cart = [];
 this.cart.push(item);

I also want to delete the element from this cart[] array based on id, the objects structure looks like:

[
    {
        id:1,
        imageUrl: "http://lorempixel.com/100/100/people?1",
        author: "Windward",
        handle: "@windwardstudios",
        body: "Looking for a better company reporting or docgen app?",
        totalLikes: 0,
        iLike: false
    },
    {
        id:2,
        imageUrl: "http://lorempixel.com/100/100/people?1",
        author: "Windward",
        handle: "@windwardstudios",
        body: "Looking for a better company reporting or docgen app?",
        totalLikes: 0,
        iLike: false
    }
]

I'm doing the pop operation to remove the object that is added to array, but unfortunately this is removing the last inserted item. Which I don't want.

this.cart.pop(); 

How can I do this in typescript?

3
  • There is no JSON in this question. JSON is a set of rules to format a string so it can be parsed as an object. The objects themselves are just objects. Commented Feb 9, 2017 at 8:06
  • var jsonString = '{ "foo": "bar" }' <-- that is JSON. var obj = { foo: "bar" } <-- that's an object. What you have there isn't JSON. Commented Feb 9, 2017 at 8:09
  • Sorry for that..but i am using var data = JSON.parse(JSON.stringify(item)); to convert it into JSON Commented Feb 9, 2017 at 8:10

1 Answer 1

8

You can use Array filter

    var idToDelete = 1;
    this.car = this.cart.filter(item=>item.id !=idToDelete );
Sign up to request clarification or add additional context in comments.

1 Comment

Can you please let me know how to use this to delete the element 1 by 1 as of no its deleting it at once.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.