Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if object exists in array of objects and update quantity?

Tags:

javascript

I have an array objArray. I want to make a function so that it will check if there is another object with the same name key. If it exists, it will add +1 in the qty key. If the object doesn't exist, it will push the new object to the array.

var objArray = [
  {"name":"bike","color":"blue","qty":2},
  {"name":"boat","color":"pink", "qty":1},
];

var carObj = {"name":"car","color":"red","qty":1};
var bikeObj = {"name":"bike","color":"blue","qty":1};
  
function checkAndAdd (obj) {
    for (var i = 0; i < objArray.length; i++) {
      if (objArray[i].name === obj.name) {
          objArray[i].qty++;
          break;
      }
      else {
          objArray.push(obj);
      }
    };
}

checkAndAdd(carObj);

console.log(objArray);

checkAndAdd(bikeObj);

console.log(objArray);

After checkAndAdd(carObj);

console.log(objArray);

Should give

[
  {"name":"car","color":"red", "qty":1},
  {"name":"bike","color":"blue","qty":2},
  {"name":"boat","color":"pink", "qty":1},
]

And fter checkAndAdd(bikeObj);

console.log(objArray);

Should give

[
  {"name":"car","color":"red", "qty":1},
  {"name":"bike","color":"blue","qty":3},
  {"name":"boat","color":"pink", "qty":1},
]

Thanks in advance!

like image 553
Joe82 Avatar asked Dec 24 '22 08:12

Joe82


1 Answers

You need to check all objects and exit the function if one item is found for incrementing the quantity.

If not found push the object.

var objArray = [{ name: "bike", color: "blue", qty: 2 }, { name: "boat", color: "pink", qty: 1 }],
    carObj = { name: "car", color: "red", qty: 1 },
    bikeObj = { name: "bike", color: "blue", qty: 1 };
  
function checkAndAdd (obj) {
    for (var i = 0; i < objArray.length; i++) {
        if (objArray[i].name === obj.name) {
            objArray[i].qty++;
            return;                             // exit loop and function
        }
    }
    objArray.push(obj);
}

checkAndAdd(carObj);
console.log(objArray);

checkAndAdd(bikeObj);
console.log(objArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 116
Nina Scholz Avatar answered May 02 '23 10:05

Nina Scholz