选择不同的子数组属性LoDash

时间:2017-03-27 15:13:16

标签: lodash distinct-values

使用以下模型结构:

prods: [{
        code: 'ABC123',
        name: 'Product 1',
        variants[{
                code: 'V123',
                name 'Var 1'
            }, {
                code: 'V456',
                name 'Var 2'
            }, {
                code: 'V789',
                name 'Var 3'
            }
        ]
    }, {
        code: 'DEF456',
        name: 'Product 2',
        variants[{
                code: 'V098',
                name 'Var 4'
            }, {
                code: 'V123',
                name 'Var 1'
            }, {
                code: 'V123',
                name 'Var 1'
            }
        ]
    }, {
        code: 'XYZ123',
        name: 'Product 3',
        variants[{
                code: 'V123',
                name 'Var 1'
            }, {
                code: 'V456',
                name 'Var 2'
            }, {
                code: 'V789',
                name 'Var 3'
            }
        ]
    }
]

是否有可能得到一组唯一的变体代码,所以期望输出给我:

  

[{code:'V123'},{code:'V456'},{code:'V789'},{code:'V098'}]

2 个答案:

答案 0 :(得分:2)

您可以将map()flatten()uniqBy()链接在一起:

_(prods)
  .map('variants')
  .flatten()
  .uniqBy('code')
  .map(i => _.pick(i, 'code'))
  .value();

第二次map()来电并非绝对必要 - 它只是为了摆脱name属性以匹配您请求的输出。

答案 1 :(得分:1)

您可以使用flatMap获取所有变体,并使用mapuniqBy进行补充,以获取所有唯一代码。

var result = _(prods)
  .flatMap('variants')
  .uniqBy('code')
  .map(_.partialRight(_.pick, 'code'))
  .value();

var prods = [{
  code: 'ABC123',
  name: 'Product 1',
  variants: [{
    code: 'V123',
    name: 'Var 1'
  }, {
    code: 'V456',
    name: 'Var 2'
  }, {
    code: 'V789',
    name: 'Var 3'
  }]
}, {
  code: 'DEF456',
  name: 'Product 2',
  variants: [{
    code: 'V098',
    name: 'Var 4'
  }, {
    code: 'V123',
    name: 'Var 1'
  }, {
    code: 'V123',
    name: 'Var 1'
  }]
}, {
  code: 'XYZ123',
  name: 'Product 3',
  variants: [{
    code: 'V123',
    name: 'Var 1'
  }, {
    code: 'V456',
    name: 'Var 2'
  }, {
    code: 'V789',
    name: 'Var 3'
  }]
}];

var result = _(prods)
  .flatMap('variants')
  .uniqBy('code')
  .map(_.partialRight(_.pick, 'code'))
  .value();
  
console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>