2016-06-07 40 views
3

我是immutable.js的新手,對於我的生活我無法弄清楚如何在地圖/列表中遍歷結果窗體,使用' fromJS'在我的狀態對象上。如何迭代immutable.js對象/ map/list

在下面的例子中,我將如何計算購物車總數? 車語法爲:{產品編號:數量,產品編號:數量的productId ..等

const INITIAL_STATE = fromJS({ 
     products: [ 
     {id: 1, name:'spaghetti', price: 25.00}, 
     {id: 2, name:'gold', price: 20.00}, 
     {id: 3, name:'rake', price: 15.00}, 
     {id: 4, name:'car', price: 10.00}, 
     {id: 5, name:'falcon', price: 5.00} 
     ], 
     cart: {1: 4, 3: 7} 
    }) 

你如何通過一個不可改變的對象重複嗎?這裏提倡的方法是在細節上的光我初中的眼睛:https://facebook.github.io/immutable-js/docs/#/List/keys

我想我找到了解決辦法,黑客攻擊的一位,但:

const total =() => { 
let total =0 
state.get('products') 
    .filter(p => { 
    return state.get('cart') 
     .has(p.get('id').toString()) 
    }) 
    .map(p => { 
    total += state.get('cart') 
     .get(p.get('id').toString()) 
     * p.get('price') 
    }) 
return total 
} 

回答

3

下面會的工作,這是稍微更簡潔。

const total = state.get('cart').reduce((total, quantity, id) => { 
    const price = state.get('products').find(product => product.get('id') == id).get('price'); 
    total += price * quantity; 
    return total; 
}, 0);