如何遍历 immutable.js 对象/地图/列表

How to iterate through an immutable.js object / map / list

我是 immutable.js 的新手,对于我的生活,我无法弄清楚如何在我的状态对象上使用 'fromJS' 遍历地图/列表。

在下面的示例中,我将如何计算购物车的总数? 购物车语法为:{productId: quantity, productId: quantity, productId.. etc

    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
}

下面的就可以了,比较简洁。

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);