Reputation: 380
I have a javascript array that is populated like this:
var orderDetails = [];
orderDetails.push({
City: "ABQ",
Banana: 5,
Mango:12
});
I am looping through a list of cities. I would like to be able to look in this array to see if the city exists and if it does, update the count of Banana and Mango. If it does not exist, I want to push the new City and Banana and Mango counts for that city into the array.
Can someone show me how this can be done? Note: I am using Server side javascript.
Thanks so much.
Upvotes: 0
Views: 92
Reputation: 2999
You can search for a city while you're looping through the list of the cities. if you find it, you can update the two value, and you can push a new object otherwise.
cities.forEach(city => {
var found = orderDetails.find(detail => detail.City === city.name);
if (found) {
found.Banana += city.banana;
found.Mango += city.mango;
} else {
orderDetails.push({
City: city.name,
Banana: city.banana,
Mango: city.mango,
});
}
});
Upvotes: 0
Reputation: 13356
You can use array.prototype.find
if the object is already in your array:
function update(arr, obj) {
var found = arr.find(o => o.City === obj.City);
if (found) {
found.Banana += obj.Banana;
found.Mango += obj.Mango;
} else {
arr.push(obj);
}
}
var orderDetails = [];
update(orderDetails, {City: "ABQ", Banana: 5, Mango:12});
update(orderDetails, {City: "XXX", Banana: 1, Mango:3});
update(orderDetails, {City: "ABQ", Banana: 5, Mango:12});
console.log(orderDetails);
Upvotes: 2