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!
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With