代码之家  ›  专栏  ›  技术社区  ›  Marcel

在平面列表选择器中使用Redux Reducer中的Lodash生成对象数组

  •  0
  • Marcel  · 技术社区  · 9 年前

    我有几个对象包含一种数据: 价格:

    'btc-usd' : 2640, 'ltc-usd': 40, ...
    

    'btc-usd': 2.533, 'ltc-usd': 10.42, ...
    

    如何获取这些对象并创建一个对象数组,如:

    [ { name: 'Bitcoin', amount: 2.533, value: 2640, id: 'btc-usd' },
     { name: 'Litecoin', amount: 10.42, value: 40, id: 'ltc-usd' }, ...
    ]
    

    对于React程序员:

    要在React中使用新的平面列表组件,需要提供一个对象数组

    <FlatList
      data={[{key: 'a'}, {key: 'b'}]}
      renderItem={({item}) => <Text>{item.key}</Text>}
    />
    

    我使用了几个还原器来存储不同种类的加密货币数据。

    'btc-usd' : 2640,'ltc-usd': 40`
    

    Reducer2存储您拥有的加密数量:

    'btc-usd': 2.533,'ltc-usd': 10.42
    

    [{名称:“比特币”,金额:2.533,价值:2640,id:“btc usd”},
    {名称:“Litecoin”,金额:10.42,价值:40,id:“ltc usd”}。。。
    ]
    

    到目前为止,我认为正确的方法是在选择器中使用重新选择。缺少的部分是createSelector中的lodash部分。 非常感谢你的帮助。

    import { createSelector } from 'reselect';
    import _ from 'lodash';
    
    export const selectRate = (state) => state.rate;
    export const selectCryptoBalance = (state) => state.cryptoBalance;
    
    
    export const createCoinArray = createSelector(
      selectRate, selectCryptoBalance,
      (rate, cryptoBalance) => {
         const coinArray = []; //better load array from state?
    
    //IMPROVEMENT NEEDED HERE
         _.forIn(selectRate, () => {
            coinArray.push(_.assign({ [selectRate.id]: 0 }, cryptoBalance));
            console.log('coinArray in loop ', coinArray);
         });
         return coinArray;
      }
    );
    

    Generate Array of Objects of different Objects Javascript 谢谢你的帮助!很多用户都会感激

    1 回复  |  直到 9 年前
        1
  •  0
  •   Shivam    9 年前

    假设您有以下对象

    prices = {'btc-usd' : 2640,'ltc-usd': 40, ... }
    rates = {'btc-usd': 2.533,'ltc-usd': 10.42, ...}
    names = {'btc-usd': 'Bitcoin' ...}
    

    你可以做的

    _.map(prices,(value,id) => ({name:names[id], amount:rates[id], value,id}))