0

I can't for the life of me retrieve a single object from an array-of-objects based on each objects unique identifier property id. The code below only returns the FIRST object in the array. I feel that I'm close to a solution, but not quite there. Any help would be greatly appreciated. Thanks in advance.

removeFromCart(item) {
    const cart = this.state.cart;
    const element = cart.filter((el, index) => {
        let indx = cart[index.id] === index[item.id];
        return indx;
    });

    cart.splice(element, 1);

    // updating the cart state
    const updateState = ({cart}) => cart;
    this.setState(updateState);
}

Data Structure Below:

[    
    {id: 1, name: "Loaded Nachos", description: "Ground beef, turkey with melted cheddar", price: 10.95},
    {id: 2, name: "Bacon Burger Combo", description: "Bacon burger with fries and slaw", price: 11.99},
    {id: 3, name: "Spicy Burrito", description: "Bean, sour cream, cheese wrap with ghost peppers", price: 7.75},
    {id: 4, name: "Mac N Cheese", description: "Cheddar jack, parm molted in harmony", price: 7.95},
    {id: 5, name: "Crab Roll", description: "New England with fries", price: 12.49},
    {id: 6, name: "BBQ Special", description: "Meadly of smoked meats (Ribs, Chicken)", price: 16.49}
]
Icarus
  • 1,627
  • 7
  • 18
  • 32
zero0rder
  • 1
  • 2
  • `index` is a number. `index.id` and `index[item.id]` will both return `undefined`. Please [read the documentation of `.filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) (and [`.splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) for that matter). – Felix Kling Apr 18 '17 at 20:21
  • `for loop` is the key word here (like `for (i = 0; i = item.Id; i++)`). You loop through the array to get what ever id you want – Penguin9 Apr 18 '17 at 20:23
  • It seems what you really want is to remove an element by ID, which you can easily do with `var newCart = cart.filter(item => item.id !== idToRemove);`. No need for `.splice`. – Felix Kling Apr 18 '17 at 20:25
  • @FelixKling The top answers to the question to which this one has been marked a duplicate are outdated and nasty. – James Apr 18 '17 at 20:27
  • @James: You find http://stackoverflow.com/a/35398031/218196 out of date? – Felix Kling Apr 18 '17 at 20:28
  • @FelixKling no, that's a good one. Shame about the accepted answer. – James Apr 18 '17 at 20:32

0 Answers0