【问题标题】:Transforming array of objects using Lodash使用 Lodash 转换对象数组
【发布时间】:2016-07-05 14:03:25
【问题描述】:

我正在尝试简化复杂的结构。
我已经尽可能地简化了它并将其简化为:

[
  {'Cells':{'Results':[
                        {'Key':'ID','Value':123},
                        {'Key':'Color','Value':'Red'},
                        {'Key':'Direction','Value':'West'}
                      ]}},
  {'Cells':{'Results':[
                        {'Key':'ID','Value':456},
                        {'Key':'Color','Value':'Green'},
                        {'Key':'Direction','Value':'East'}
                      ]}}
]

我的 lodash 缺乏技能,我需要帮助将上述内容变成这样:

[
  {'ID':123, 'Color':'Red', 'Direction':'West'},
  {'ID':456, 'Color':'Green', 'Direction':'East'}
]

顺便提一下,键的数量因对象而异。至少,它可能只有 ID,但有些可能会超过示例中的这三个。

【问题讨论】:

    标签: javascript arrays object underscore.js lodash


    【解决方案1】:

    在纯 Javascript 中,您可以使用两个嵌套循环。

    var array = [{ 'Cells': { 'Results': [{ 'Key': 'ID', 'Value': 123 }, { 'Key': 'Color', 'Value': 'Red' }, { 'Key': 'Direction', 'Value': 'West' }] } }, { 'Cells': { 'Results': [{ 'Key': 'ID', 'Value': 456 }, { 'Key': 'Color', 'Value': 'Green' }, { 'Key': 'Direction', 'Value': 'East' }] } }],
        condensed = array.map(function (a) {
            var o = {};
            a.Cells.Results.forEach(function (b) {
                o[b.Key] = b.Value;
            });
            return o;
        });
    
    console.log(condensed);

    【讨论】:

      【解决方案2】:

      使用 Lodash 的解决方案:

      var result = _.chain(data)
          .map('Cells.Results')
          .map(res => _.zipObject(_.map(res,"Key"), _.map(res,"Value")))
          .value();
      

      【讨论】:

        【解决方案3】:

        应该这样做(虽然我不确定它是否比普通的 javascript 更好)

        _.chain(array)
         .pluck('Cells')
         .pluck('Results')
         .map(function (value) { return _.object(_.map(value, _.values)); })
         .value()
        

        【讨论】:

        • 不幸的是,这不会输出正确的格式。每个数组对象只有最后一个键,没有值(???)
        • 对于您提供的示例输入,上面的代码输出完全符合您的要求。
        【解决方案4】:

        这是使用lodash fp 的另一种选择。

        var result = map(compose(
          mapValues('Value'),
          keyBy('Key'),
          iteratee('Cells.Results')
        ))(data);
        

        var data = [{
          'Cells': {
            'Results': [{
              'Key': 'ID',
              'Value': 123
            }, {
              'Key': 'Color',
              'Value': 'Red'
            }, {
              'Key': 'Direction',
              'Value': 'West'
            }]
          }
        }, {
          'Cells': {
            'Results': [{
              'Key': 'ID',
              'Value': 456
            }, {
              'Key': 'Color',
              'Value': 'Green'
            }, {
              'Key': 'Direction',
              'Value': 'East'
            }]
          }
        }];
        
        var { compose, map, iteratee, keyBy, mapValues } = _;
        
        var result = map(compose(
          mapValues('Value'),
          keyBy('Key'),
          iteratee('Cells.Results')
        ))(data);
        
        document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
        <script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
        <script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.fp.js"></script>

        【讨论】:

          【解决方案5】:

          另一个答案,使用 map 和 reduce

              var initial_array=[
                {'Cells':{'Results':[
                                  {'Key':'ID','Value':123},
                                  {'Key':'Color','Value':'Red'},
                                  {'Key':'Direction','Value':'West'}
                                ]}},
                {'Cells':{'Results':[
                                  {'Key':'ID','Value':456},
                                  {'Key':'Color','Value':'Green'},
                                  {'Key':'Direction','Value':'East'}
                                ]}}
              ];
          
               function mergeObj(accumulator,current){
                 accumulator[current['Key']]=current['Value'];
                 return accumulator;  
               }
          
               function getResults(obj){
                 return obj.Cells.Results.reduce(mergeObj,{});
               }
          
               var transformed_array=_(initial_array).map(getResults).value();
               console.log(transformed_array);
          &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"&gt;&lt;/script&gt;

          【讨论】:

            猜你喜欢
            • 2016-08-06
            • 1970-01-01
            • 2019-01-26
            • 1970-01-01
            • 2019-04-18
            • 2019-08-09
            • 1970-01-01
            相关资源
            最近更新 更多