如何根据唯一属性值从对象数组中检索单个对象

时间:2017-04-18 20:18:22

标签: javascript arrays json reactjs setstate

我不能为我的生活从基于每个对象唯一标识符属性id的对象数组中检索单个对象。下面的代码只返回数组中的FIRST对象。我觉得我接近一个解决方案,但并不完全在那里。任何帮助将不胜感激。提前谢谢。

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);
}

以下数据结构:

[    
    {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}
]

0 个答案:

没有答案