我有以下数组,包括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
?
答案 0 :(得分:4)
不使用外部库,使用新的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);
答案 1 :(得分:1)
这是一个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>
使用lodash / fp可能会更简单,但我从来没有让它正常工作。我可能没有花太多时间在上面,因为我是JS的另一个FP库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>
我猜Lodash / fp代码可能看起来很相似,只是你必须用map
替换第一个mapValues
。