我有一个由name
、age
和department
组成的数组数组
[[ "Kevin", 22,"Psychology" ],
[ "Cathy", 26, "Psychology" ],
[ "David", 31, "Engineering" ],
[ "Christine", 23, "Engineering" ]]
我想创建一个基于唯一的departments
的地图,如下所示:
{ Psychology: [
{ name: "Cathy", age: 26 },
{ name: "Kevin", age: 22 } ]
},
{ Engineering: [
{ name: "Christine", age: 23 },
{ name: "David", age: 31 } ]
}
数组中的department
索引总是相同的。如何利用lodash
实现这一点?
发布于 2018-04-23 15:33:43
在不使用外部库的情况下,使用这样的新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);
发布于 2018-04-23 16:25:19
这里有一个房客解决方案:
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>
它可能会变得更简单,但我从来没有得到正确的工作。我可能没有花太多时间在上面,因为我是JS,兰达的另一个FP库的作者之一。上面的解决方案是通过翻译我用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>
我猜想,尽管您必须用mapValues
替换第一个mapValues
,但该代码看起来可能非常相似。
https://stackoverflow.com/questions/49984612
复制相似问题