2017-03-06 1 views
0

쇼핑 카트입니다.일치하는 속성을 찾으려면 객체 리터럴 배열을 반복 실행하려면 어떻게해야합니까?

regularListings에서 항목의 가격을 검색하고이를 사용하여 장바구니 합계를 계산하고 싶습니다.

카트 '마이클'의 첫 번째 항목은 고객의 이름입니다.

어떻게 이것을 JavaScript로 할 수 있습니까?

'use strict' 

const listing = 
    (name, price) => ({ 
    name, 
    price 
    }) 

const cart = 
    (customer, ...items) => ({ 
    customer, 
    items 
    }) 

const listedPrice = 
    listing => 
    name => 
     name === listing.name 
     ? listing.price 
     : 0 

const regularListings = [ 
    listing('detergent', 10), 
    listing('hennessey', 100), 
    listing('carlo rozzi', 20), 
    listing('coffee', 5), 
    listing('cookies', 6), 
    listing('mountain dew', 2) 
] 

const carts = [ 
    cart(
    'michael', 
    'coffee', 
    'hennessey', 
    'coffee', 
    'hennessey', 
    'coffee', 
    'hennessey' 
) 
] 
+1

을 계산할 수 있습니다 : 개체 속성이 보장 된 주문이 없습니다. 카트는 개체가 아닌 배열이어야합니다. – Pointy

답변

3

당신은 regularListings을 줄이고, 당신은 문제로 실행거야 합계

const regularListings = [ 
    listing('detergent', 10), 
    listing('hennessey', 100), 
    listing('carlo rozzi', 20), 
    listing('coffee', 5), 
    listing('cookies', 6), 
    listing('mountain dew', 2) 
] 

const total = regularListings.reduce((state, item) => state + item, 0); 
+2

ES6 화살표 표기법을 사용하려면 :'regularListings.reduce ((total, item) => total + item.price, 0); ' – seth10

+0

또한'total' 값이기 때문에 0이 존재합니다. 확실하지 않은 경우를 대비해서 시작하십시오. – seth10

+0

@setht 친절한 제안에 감사드립니다. – Burimi

관련 문제