Baz Baz - 1 month ago 6
Javascript Question

Update or add value to list

How would you either update

inventory
(based on name) or add if name not found.

var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];


For example, the following will update the inventory:

const fruit = {name: 'bananas', quantity: 1}
inventory = inventory.map(f => f.name===fruit.name ? fruit : f);


and this could be used to add to the inventory:

const fruit = {name: 'oranges', quantity: 2}
if (!inventory.find(f => f.name===fruit.name)) inventory.push(fruit)


but I'm looking for a solution which can do both and which preferably uses arrow functions rather than indexes - if possible.

Answer

You can use findIndex:

var idx = inventory.findIndex(f => f.name === fruit.name);
inventory[idx < 0 ? inventory.length : idx] = fruit;

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

var fruit = {name: 'bananas', quantity: 1}

var idx = inventory.findIndex(f => f.name === fruit.name);
inventory[idx < 0 ? inventory.length : idx] = fruit;

var fruit = {name: 'oranges', quantity: 2}

var idx = inventory.findIndex(f => f.name === fruit.name);
inventory[idx < 0 ? inventory.length : idx] = fruit;

console.log(inventory);

In case you want to merge two arrays of objects (instead of a single object to an array), then this approach would be quadratic. You should see JavaScript merging objects by id instead.

Comments