[英]Create a Map of Objects from an Array via Lodash
I have the following array of arrays consisting of a name
, age
, and department
我有以下由
name
, age
和department
组成的数组数组
[[ "Kevin", 22,"Psychology" ],
[ "Cathy", 26, "Psychology" ],
[ "David", 31, "Engineering" ],
[ "Christine", 23, "Engineering" ]]
I want to create a map based on the unique departments
that would look like this: 我想根据如下所示的独特
departments
创建地图:
{ Psychology: [
{ name: "Cathy", age: 26 },
{ name: "Kevin", age: 22 } ]
},
{ Engineering: [
{ name: "Christine", age: 23 },
{ name: "David", age: 31 } ]
}
The index of department
in the array will always be same. 数组中
department
的索引将始终相同。 How can this be done utilizing lodash
? 如何使用
lodash
完成此操作?
Without using a external library, using new ESNext stuff like this is pretty easy. 在不使用外部库的情况下,使用这样的新ESNext东西非常容易。
const data = [ [ "Kevin", 22,"Psychology" ], [ "Cathy", 26, "Psychology" ], [ "David", 31, "Engineering" ], [ "Christine", 23, "Engineering" ]]; const result = data.reduce((a, v) => { const [name,age,dept] = v; (a[dept] = a[dept] || []).push({name,age}); return a; }, {}); console.log(result);
Here is a lodash solution: 这是一个lodash解决方案:
const {flow, groupBy, nth, mapValues, map, zipObject} = _ const transform = flow( people => groupBy(people, p => nth(p, 2)), grouped => mapValues(grouped, dept => map( dept, person => zipObject(['name', 'age'], person) )) ) const people = [["Kevin", 22, "Psychology"], ["Cathy", 26, "Psychology"], ["David", 31, "Engineering"], ["Christine", 23, "Engineering"]] console.log(transform(people))
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
It would probably be made simpler with lodash/fp, but I've never gotten that working correctly. lodash / fp可能会使它更简单,但是我从来没有正确地工作过。 I probably haven't spent much time on it because I'm one of the authors of another FP library for JS, Ramda .
我可能没有花太多时间,因为我是JS另一个FP库Ramda的作者之一。 The solution above was created by translating my first code, written with Ramda:
上面的解决方案是通过翻译我用Ramda编写的第一个代码创建的:
const {pipe, groupBy, nth, map, zipObj} = R; const transform = pipe( groupBy(nth(2)), map(map(zipObj(['name', 'age']))) ) const people = [["Kevin", 22, "Psychology"], ["Cathy", 26, "Psychology"], ["David", 31, "Engineering"], ["Christine", 23, "Engineering"]] console.log(transform(people))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
I'm guessing that lodash/fp code would probably look pretty similar, except that you'd have to replace the first map
with mapValues
. 我猜测lodash / fp代码可能看起来非常相似,只是您必须将第一个
map
替换为mapValues
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.