gpt4 book ai didi

javascript - 按属性映射集合项 lodash

转载 作者:行者123 更新时间:2023-12-02 14:17:24 25 4
gpt4 key购买 nike

数据如下:

[
{type: "one", ...fields},
{type: "one", ...fields},
{type: "two", ...fields}
]

应转换为:

{
one: [...itemsWithType == "one"],
two: [...itemsWithType == "two"]
}

我知道如何在 vanillas ES5/ES6 中执行此操作..我正在寻找特殊的 lodash 命令。我只是迷失在文档中,也许有人可以告诉我这种准备工作是如何称呼的,我可以注意到它。

我正在寻找一个简单的 lodash 函数,例如

mapByProp(collection, 'type');

是的,可以这样写:

const mapByProp = (array, t) => {
return array.reduce((m, i) => {
!m[i[t]] && m[i[t]] = [];
m[i[t]].push(i);

return m;
}, {});
};

但是如果有lodash函数,我很乐意使用它

最佳答案

您可以使用_.groupBy :

var a = [
{type: "one", wow: 1},
{type: "one", wow: 2},
{type: "two", wow: 3}
];

var result = _.groupBy(a, 'type');

关于javascript - 按属性映射集合项 lodash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38917507/

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