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?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Rohitesh
  • 1,514
  • 7
  • 28
  • 51
  • 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_. – Cerbrus Feb 09 '17 at 08:06
  • `var jsonString = '{ "foo": "bar" }'` <-- that is JSON. `var obj = { foo: "bar" }` <-- that's an object. What you have there isn't JSON. – Cerbrus Feb 09 '17 at 08:09
  • Sorry for that..but i am using var data = JSON.parse(JSON.stringify(item)); to convert it into JSON – Rohitesh Feb 09 '17 at 08:10

1 Answers1

8

You can use Array filter

    var idToDelete = 1;
    this.car = this.cart.filter(item=>item.id !=idToDelete );
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
  • 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. – Rohitesh Feb 09 '17 at 08:27