javascript - 如何遍历 immutable.js 对象/ map /列表

标签 javascript list dictionary immutable.js

我是 immutable.js 的新手,在我的一生中,我无法弄清楚如何在我的状态对象上使用“fromJS”来迭代结果形式的 map /列表。

在下面的示例中,我将如何计算购物车的总数? 购物车语法为:{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}
    })

这里如何遍历不可变对象(immutable对象)?此处介绍的方法对我初级的眼睛来说很详细: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);

关于javascript - 如何遍历 immutable.js 对象/ map /列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37671739/

相关文章:

javascript - 表达式 console.log(1&3); 背后的数学原理是什么?

javascript - 如何从场景中删除对象

javascript - angularjs 选择下拉验证

python - 在 pandas 中,如何从字典列表创建数据框?

javascript - 我想使用 JQuery 创建一个 Twitter 小部件 - 我应该从哪里开始?

Java,类的多个实例重置为最新创建的实例

python - pandas:将列表转换为 int64index

list - 删除 Prolog 中元素的第一次出现

python - 垂直打印列表字典

c# - 将字典对象转换成Json字符串