gpt4 book ai didi

javascript - Ramda GroupBy - 如何按任何 Prop 分组

转载 作者:搜寻专家 更新时间:2023-11-01 05:03:11 25 4
gpt4 key购买 nike

给出:

interface Dict {
[key: string]: any
}

const data: Dict[] = [
{ id: 'a' },
{ id: 'b', b: 'something' },
{ id: 'c', b: 'else' },
{ id: 'd', extra: 'hello world' },
{ id: 'e' },
];

未指定这些 Dict 对象的键...

我怎样才能得到这个结果?

const result = {
id: ['a', 'b', 'c', 'd', 'e'],
b: ['something', 'else'],
extra: ['hello world'],
// ... and any other possible key
}

最佳答案

您可以将对象展平为成对列表,将其分组,然后将成对转换回值:

const data = [
{ id: 'a' },
{ id: 'b', b: 'something' },
{ id: 'c', b: 'else' },
{ id: 'd', extra: 'hello world' },
{ id: 'e' },
];


let z = R.pipe(
R.chain(R.toPairs),
R.groupBy(R.head),
R.map(R.map(R.last))
)

console.log(z(data))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

关于javascript - Ramda GroupBy - 如何按任何 Prop 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56646659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com