Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefer destructuring es-lint error

I have this function:

const calculateTotal = (items) => {
  return items.reduce((totalPrice, basketItem) => {
    const price = basketItem.product.price;
    const quantity = basketItem.quantity;
    const total = price * quantity;
    return totalPrice + total;
  }, 0);
};

How do I fix this with ES6+ destructuring?

I know I need something like (on line 4):

const { basketItem: quantity } = quantity;

but I can't get line 3 working

like image 278
The Walrus Avatar asked Jan 09 '18 14:01

The Walrus


2 Answers

Based on the what you attempted doing, you could do this to get price from product and quantity from basketItem without having to declare variables on two separate lines.

const calculateTotal = (items) => {
  return items.reduce((totalPrice, basketItem) => {
    const { product: { price }, quantity } = basketItem;

    const total = price * quantity;
    return totalPrice + total;
  }, 0);
};
like image 113
codejockie Avatar answered Sep 29 '22 10:09

codejockie


const quantity=basketItem.quantity;

below this destructuring method :

const {quantity}=basketItem;
like image 39
SM Chinna Avatar answered Sep 29 '22 09:09

SM Chinna