Задача. Общая стоимость товара

const products = [
  { name: "Radar", price: 1300, quantity: 4 },
  { name: "Scanner", price: 2700, quantity: 3 },
  { name: "Droid", price: 400, quantity: 7 },
  { name: "Grip", price: 1200, quantity: 9 },
];

function calculateTotalPrice(productName) {
const totalPrice = 0;
for (const product of products){
if(product[productName]){
totalPrice[productName] = product.price * product.quantity
}
console.log(totalPrice[productName] = product.price * product.quantity)
}
return totalPrice;
}

console.log(calculateTotalPrice('Radar'))

помогите понять как в totalPrice поместить общую сумму


Ответы (2 шт):

Автор решения: Артём

Вы можете использовать функцию .find в JavaScript, для поиска необходимого вам продукта:

const products = [
  { name: "Radar", price: 1300, quantity: 4 },
  { name: "Scanner", price: 2700, quantity: 3 },
  { name: "Droid", price: 400, quantity: 7 },
  { name: "Grip", price: 1200, quantity: 9 },
];
    
function calculateTotalPrice(productName) {
    const product = products.find(p => p.name == productName);
    return product.price * product.quantity;
};
    
console.log(calculateTotalPrice('Radar'))
→ Ссылка
Автор решения: максим
const products = [
  { name: "Radar", price: 1300, quantity: 4 },
  { name: "Scanner", price: 2700, quantity: 3 },
  { name: "Droid", price: 400, quantity: 7 },
  { name: "Grip", price: 1200, quantity: 9 },
];

function calculateTotalPrice(productName) {
for(const product of products){
let totalPrice = product.price * product.quantity;
if(productName === product.name){
return totalPrice;
}
}
return 0;
}

вот ответ

→ Ссылка