Lodash:如何按一组对象分组?

时间:2019-12-22 08:48:24

标签: typescript lodash

我有一个对象数组:

[
    {
       product: "ABC",
       features: [1,2,3]
      },
    {
       product: "CDE",
       features: [1,2]
      },
      {
       product: "XYZ",
       features: [3,4,5]
      }
]

我正在寻找一种方法来帮助打字稿中的Lodash按功能列表将此json分组,并得出以下结果:

[
    {
       feature: 1,
       Products: ["ABC","CDE"]
      },
      {
       feature: 2,
       Products: ["ABC","CDE"]
      },
      {
       feature: 3,
       Products: ["ABC","XYZ"]
      },
      {
       feature: 4,
       Products: ["XYZ"]
      },
      {
       feature: 5,
       Products: ["XYZ"]
      }
]

1 个答案:

答案 0 :(得分:2)

我认为还没有一个可以选择使用的<div class="border">SignUp</div>功能来满足您的特定情况。所以我写了lodash是执行您所期望的功能。

fn
function fn(input) {
  const allFeatures = input.reduce((features, cur) => {
    return _.uniq(_.concat(features, cur.features))
  }, [])

  return allFeatures.map(feature => ({
    feature,
    Products: input.filter(prod => prod.features.includes(feature)).map(x => x.product)
  }))
}





const input = [
  {
    product: 'ABC',
    features: [1, 2, 3]
  },
  {
    product: 'CDE',
    features: [1, 2]
  },
  {
    product: 'XYZ',
    features: [3, 4, 5]
  }
]

const expected = [
  {
    feature: 1,
    Products: ['ABC', 'CDE']
  },
  {
    feature: 2,
    Products: ['ABC', 'CDE']
  },
  {
    feature: 3,
    Products: ['ABC', 'XYZ']
  },
  {
    feature: 4,
    Products: ['XYZ']
  },
  {
    feature: 5,
    Products: ['XYZ']
  }
]
console.log('equal expected: ', _.isEqual(fn(input), expected))

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
function fn(input) {
  const allFeatures = input.reduce((features, cur) => {
    return _.uniq(_.concat(features, cur.features))
  }, [])

  return allFeatures.map(feature => ({
    feature,
    Products: input.reduce((prods, cur) => cur.features.includes(feature) ?  prods.concat(cur.product) : prods, [])
  }))
}





const input = [
  {
    product: 'ABC',
    features: [1, 2, 3]
  },
  {
    product: 'CDE',
    features: [1, 2]
  },
  {
    product: 'XYZ',
    features: [3, 4, 5]
  }
]

const expected = [
  {
    feature: 1,
    Products: ['ABC', 'CDE']
  },
  {
    feature: 2,
    Products: ['ABC', 'CDE']
  },
  {
    feature: 3,
    Products: ['ABC', 'XYZ']
  },
  {
    feature: 4,
    Products: ['XYZ']
  },
  {
    feature: 5,
    Products: ['XYZ']
  }
]
console.log('equal expected: ', _.isEqual(fn(input), expected))

我很想知道是否有更清洁的方法。