[英]merging arrays using lodash
I have this set of an array of objects: 我有一组对象数组:
let x = [{ CategoryName: 'abc', Items: ['3A'] }, { CategoryName: 'xyz', Items: ['5Z'] }, { CategoryName: 'abc', Items: ['6B'] }, { CategoryName: 'abc', Items: ['9C'] }, { CategoryName: 'xyz', Items: ['1X'] } ];
what I want is: 我想要的是:
[
{CategoryName:'abc',Items['3A','6B','9C']},
{CategoryName:'xyz',Items['1X','5Z']}
]
How I can I achieve this using lodash
? 我如何使用
lodash
实现此lodash
?
You can group
it by CategoryName and flatMap
that result by Items
. 您可以将其按CategoryName
group
,并将flatMap
按Items
group
。 That's it! 而已!
_(x).groupBy('CategoryName').map((v, k)=> ({CategoryName: k, Items: _.flatMap(v, 'Items')})).value()
Working demo: 工作演示:
let x = [{"CategoryName":"abc","Items":["3A"]},{"CategoryName":"xyz","Items":["5Z"]},{"CategoryName":"abc","Items":["6B"]},{"CategoryName":"abc","Items":["9C"]},{"CategoryName":"xyz","Items":["1X"]}], res; res = _(x).groupBy('CategoryName').map((v, k)=> ({CategoryName: k, Items: _.flatMap(v, 'Items')})).value(); console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
With lodash you could do this also with _.groupBy
and mergeWith
: 使用lodash,您也可以使用
_.groupBy
和mergeWith
来执行此mergeWith
:
let data = [{ CategoryName: 'abc', Items: ['3A'] }, { CategoryName: 'xyz', Items: ['5Z'] }, { CategoryName: 'abc', Items: ['6B'] }, { CategoryName: 'abc', Items: ['9C'] }, { CategoryName: 'xyz', Items: ['1X'] } ]; const result = _.map(_.groupBy(data, 'CategoryName'), x => _.mergeWith(...x, (o,s) => _.isArray(s) ? o.concat(s) : o)) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Or with _.transform
: 或使用
_.transform
:
let data = [{ CategoryName: 'abc', Items: ['3A'] }, { CategoryName: 'xyz', Items: ['5Z'] }, { CategoryName: 'abc', Items: ['6B'] }, { CategoryName: 'abc', Items: ['9C'] }, { CategoryName: 'xyz', Items: ['1X'] } ]; const result = _.transform(data, (r, {CategoryName, Items}) => { r[CategoryName] = r[CategoryName] || ({CategoryName}) r[CategoryName].Items = [...Items, ...r[CategoryName].Items || []] }, {}) console.log(Object.values(result))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Or simply with just ES6 and Array.reduce
: 或仅使用ES6和
Array.reduce
:
let data = [{ CategoryName: 'abc', Items: ['3A'] }, { CategoryName: 'xyz', Items: ['5Z'] }, { CategoryName: 'abc', Items: ['6B'] }, { CategoryName: 'abc', Items: ['9C'] }, { CategoryName: 'xyz', Items: ['1X'] } ]; const result = data.reduce((r,{CategoryName, Items}) => { r[CategoryName] = r[CategoryName] || ({CategoryName}) r[CategoryName].Items = [...Items, ...r[CategoryName].Items || []] return r }, {}) console.log(Object.values(result))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.