I have a list of products structured like this:
var itemsList = [
{
id: 'as5',
name: 'Coca-Cola',
price: 17.5,
unit: 'Bottles',
quantity: 23
},
{
id: 'q7s',
name: 'Cheese',
price: 34.8,
unit: 'Kilos',
quantity: 6
},
{
id: 'pa5',
name: 'Bread',
price: 3.5,
unit: 'Pieces',
quantity: 100
},
{
id: 'capu2',
name: 'Oil',
price: 21,
unit: 'Bottle',
quantity: 10
},
{
id: 'bon4',
name: 'Bonafont Water',
price: 25,
unit: 'Jug',
quantity: 12
},
{
id: 'tun1',
name: 'Tuna',
price: 11,
unit: 'Can',
quantity: 30
},
];
I want to locate an item by its ID and decrease the quantity by one.
This is my current approach using lodash 3.10:
var item = _.find(itemsList, {id: 'tun1'});
item.quantity--;
itemsList.splice(_.findIndex(itemsList, {id: 'tun1'}), 1, item);
However, I find this method inefficient as it requires multiple operations and iteration with splice.
Could someone suggest a more optimized solution in plain ES5 JS?