To calculate the value of an array of objects with a specific key, you can use a loop to iterate through each object in the array and add up the values of the specified key. For example, if you have an array of objects with a “price” key, you can calculate the total price like this:
let items = [
{name: 'Item 1', price: 10},
{name: 'Item 2', price: 20},
{name: 'Item 3', price: 30}
];
let totalPrice = 0;
for (let i = 0; i < items.length; i++) {
totalPrice += items[i].price;
}
console.log(totalPrice); // Output: 60
This will loop through each object in the ‘items’ array and add up the value of the “price” key, resulting in a total price of 60.
For better and simple way, you can use the ‘reduce’ method to calculate the total value of an array of objects with a specific key. Here’s an example:
let items = [
{name: 'Item 1', price: 10},
{name: 'Item 2', price: 20},
{name: 'Item 3', price: 30}
];
let totalPrice = items.reduce((total, item) => total + item.price, 0);
console.log(totalPrice); // Output: 60
The ‘reduce’ method takes a function as its first argument, which is called for each element in the array. The second argument is the initial value of the accumulator (in this case, 0). The function takes two arguments: the accumulator (which starts at the initial value) and the current element in the array. In this case, we’re adding the value of the “price” key to the accumulator for each element. At the end, the ‘reduce’ method returns the final value of the accumulator, which is the total price. This is a more concise method compared to using a loop.