【问题标题】:How to unpivot a collection/array with Lodash.js?如何使用 Lodash.js 对集合/数组进行反透视?
【发布时间】:2020-09-30 15:57:10
【问题描述】:

我是 JavaScript 的初学者,我想取消透视集合/数组。

我有一个这样的集合/数组:

[
  { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
  { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
]

我想转换我的集合/数组以获得类似的东西:

var a = [
  { 'produit': 'a', 'attribute': 'color', 'value': 'white' }, 
  { 'produit': 'a', 'attribute': 'material', 'value': 'leather' }, 
  { 'produit': 'b', 'attribute': 'color', 'value' :'black' },
  { 'produit': 'b', 'attribute': 'material', 'value': 'wool' }
]

我试图在 lodash.js 的文档中找到一些东西,但我不知道该怎么做。

【问题讨论】:

    标签: javascript lodash unpivot


    【解决方案1】:

    您可以使用_.flatMap(),通过destructuring produit 键为每个对象,然后将mapping keys/values 剩余对象用于包含produit 键的新对象,键为attribute 键和 value 键的值:

    const arr = [
      { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
      { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
    ];
    
    const res = _.flatMap(
      arr,
      ({produit, ...r}) => _.map(_.entries(r), ([attribute, value]) => ({produit, attribute, value}))
    );
    
    console.log(res);
    <script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

    现在 JS 有很多内置的数组函数,所以在 vanilla JS 中也可以使用类似的方法实现上述功能:

    const arr = [
      { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
      { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
    ];
    
    const res = arr.flatMap(
      ({produit, ...r}) => Object.entries(r).map(([attribute, value]) => ({produit, attribute, value}))
    );
    
    console.log(res);
    <script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

    【讨论】:

      【解决方案2】:

      你不需要 lodash。您可以使用对象销毁和缩减轻松做到这一点。

      const original = [
        { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
        { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
      ]
      
      const altered = original.reduce((acc, item) =>
        (({ produit, ...rest }) =>
          Object.entries(rest).reduce((result, [attribute, value]) =>
            [ ...result, { produit, attribute, value } ], acc))(item), []);
      
      console.log(altered);
      .as-console-wrapper { top: 0; max-height: 100% !important; }

      【讨论】:

        猜你喜欢
        • 2022-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-20
        • 1970-01-01
        相关资源
        最近更新 更多