check if an object with a specific key value exists in an array of objects

  • A+
Category:Languages

I'm trying to check if an array of items contains an object with a specific key value, and if it does, just update the array of items with the new item object

[{name: example1, quantity: 2},{name: example2, quantity: 3},{name: example3, quantity: 5}] 

so if for example I'm pushing an object with the same name of "example1", I want to check if it does exist in the array and if it does, just update it with the new object with the new quantity for example.

I tried to explain what I want as best as I can, please let me know if you need more clarification.

 


You can use a simple combination of Array#some() and Array#find() methods:

if (data.some(o => o.name == toPush.name)) {   data.find(o => o.name == toPush.name).quantity = toPush.quantity; } 

Where data is your array and toPush is the object you are trying to update.

Demo:

var data = [{   name: "example1",   quantity: 2 }, {   name: "example2",   quantity: 3 }, {   name: "example3",   quantity: 5 }];  let toPush = {   name: "example2",   quantity: 10 };  if (data.some(o => o.name == toPush.name)) {   data.find(o => o.name == toPush.name).quantity = toPush.quantity; }  console.log(data);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: