2

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.

2
  • Do these objects only have name and quantity keys? If so, then you should just use a mapping, not an array of objects. If there's more keys in the objects, what would happen to those keys when you merge? Commented Oct 26, 2018 at 9:55
  • 1
    You should really add a) a before/after example of your array of objects (because, based on the answers, I'm not sure people understand what you want, and b) your own attempted solution. Commented Oct 26, 2018 at 10:03

9 Answers 9

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

I think this is the only answer that understands the question
@Andy Thank you, yes, he should check if the searched object exists and updates it.
3
let arr1 = [{name: 'example1', quantity: 2},{name: 'example2', quantity: 3},{name: 'example3', quantity: 5}];
let obj1 = {name: 'example1', quantity: 5};
if(arr1.filter(item=> item.name === obj1.name).length==0){
  arr1.push(obj1);
}
else{
  arr1.filter(item=> item.name === obj1.name)[0].quantity = obj1.quantity;
}

Comments

2

You can use Array.find() for that update and pushing the unique objects. You can also use existObj = obj; so that all the updated properties of obj is set on the existing object and not just one property (as it is now with quantity). But if you need only the quantity property to get updated then use existObj.quantity = obj.quantity;

let arr = [{name: 'example1', quantity: 2},{name: 'example2', quantity: 3},{name: 'example3', quantity: 5}];
let obj = {name: 'example1', quantity: 5};
var existObj = arr.find(({name}) => name === obj.name);
if(existObj){
  existObj = obj;
} else {
  arr.push(obj);
}
console.log(arr);

Comments

1

I'd use the Array.prototype.some() function:

const arr = [{name: 'example1', quantity: 2},{name: 'example2', quantity: 3},{name: 'example3', quantity: 5}]


var result = arr.some(e => e.hasOwnProperty('name') && e.hasOwnProperty('quantity'));

console.log("The array contains an object with a 'name' and 'quantity' property: " + result);

Comments

1

Better use Array.findIndex() with this

let myArray = [{name: 'example1', quantity: 2},{name: 'example2', quantity: 3},{name: 'example3', quantity: 5}];
const newItem = { name: 'example1', quantity: 5 };
const indexOfItem = myArray.findIndex(item => item.name === item.name);

if(indexOfItem === -1) { // not existing
  myArray.push(newItem);
else {
  myArray[indexOfItem] = newItem;
} 

Comments

1

You can create "push" function and pass in the object you want to add/update. Function will take care if it needs to add / update arr by using "find". Also, this will take care of all properties not just "quantity"

var arr = [{name: 'example1', quantity: 2},{name: 'example2', quantity: 3},{name: 'example3', quantity: 5}]

function push(obj) {
  var data = arr.find(({name}) => name == obj.name) || (arr = arr.concat({})).slice(-1)[0];
  Object.assign(data, obj)
}

push({ name: 'example11', quantity: 100 })
console.log('example11 added', arr)

push({ name: 'example1', quantity: 100 })
console.log('example1 updated', arr)

Comments

1

you can use Array.forEach which iterates through each object, and we can update existing array with using the index param.

Please see the below code.

var data = [{name: "example1", quantity: 2},{name: "example2", quantity: 3},{name: "example3", quantity: 5}]

var object = {name: "example1", quantity: 14}

data.forEach((o,index) => {
  if(o.name === object.name){
    o.quantity = object.quantity
    return data[index] = o
  }else{
    data[index] = o
  }
})


console.log("updated data array =>", data)

Comments

0

In case if you want to match both object key & values, this will work.

let myArray = [{name: 'example1', quantity: 2},{name: 'example2', quantity: 3},{name: 'example3', quantity: 5}];
let newObj = { name: 'example1', quantity: 5 };

let myArrayJSON = JSON.stringify(myArray);
let newObjJSON = JSON.stringify(newObj);

if(myArrayJSON.indexOf(newObjJSON) === -1){
   myArray.push(newObj); 
}

Comments

0

var ObjectArray = [{name: 'example1', quantity: 2},{name: 'example2', quantity: 3},{name: 'example3', quantity: 5}]
    console.log(ObjectArray)
   var name = 'example2'
   var index = ObjectArray.findIndex(product => product.name == name);
   if(index>=0){
        console.log("Found and updated ObjectArray")
       ObjectArray.splice(index, 1, {name: 'example2', quantity: 8});
       console.log(ObjectArray)
   }
   else{
      console.log("not found")
   }

1 Comment

Welcome to SO! This code might be a good answer, but it would be better to avoid code-only answers and provide some explanation/context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.