Ziad Ali
Ziad Ali

Reputation: 55

how can i do a math in an array of objects?

I want to calculate the qty * price in totalPrice and it gives me "qty is not defined", how can i do it?

let products = [
{
    title: "Sunglasses",
    imgURL: "images/Products/sunglasses.jpg",
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
    price:80,
    qty:1,
    totalPrice: qty * price,
    id: 1
}]

it supposed to be a shopping cart so the qty changes and i want the totalPrice to be in the object because i suppose to put every totalPrice of the products in cart together to get the total price of the whole cart

Upvotes: 0

Views: 531

Answers (2)

trincot
trincot

Reputation: 350310

You are referencing variables (which don't exist), not properties.

There are a few ways to handle this. For instance, you could add the total price in a second step:

let products = [
{
    title: "Sunglasses",
    imgURL: "images/Products/sunglasses.jpg",
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
    price:80,
    qty:1,
    id: 1
}]

for (let product of products) product.totalPrice = product.qty * product.price;

Or you can have it calculated dynamically with a getter:

let products = [
{
    title: "Sunglasses",
    imgURL: "images/Products/sunglasses.jpg",
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
    price:80,
    qty:1,
    get totalPrice() { return this.qty * this.price },
    id: 1
}]

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28414

You can use Array#map:

const products = [
  {
    title: "Sunglasses",
    imgURL: "images/Products/sunglasses.jpg",
    desc: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Aut nulla adipisci fugiat pariatur recusandae repudiandae fuga molestias doloremque itaque obcaecati.",
    price:80,
    qty:1,
    id: 1
  }
];

const res = products.map(product => 
  ({ ...product, totalPrice: product.qty * product.price })
);

console.log(res);

Upvotes: 1

Related Questions