我对 lodash 相当陌生,怀疑它可以帮助我按照我想要的方式转换数据。我一直在读lodash docs但说实话,它并没有被理解,我没有看到我需要的正确操作组合。
这是我想做的:
var configs = [ {
configId: 1,
options: [ {categoryId: 1, id: 100},
{categoryId: 2, id: 200},
{categoryId: 3, id: 300} ] },
{
configId: 2,
options: [ {categoryId: 1, id: 105},
{categoryId: 2, id: 210} ] },
{
configId: 3,
options: [ {categoryId: 2, id: 200},
{categoryId: 1, id: 165},
{categoryId: 3, id: 300} ] }
];
// I want the above to look like this:
/*
[ {categoryId: 1, ids: [100, 105, 165]},
{categoryId: 2, ids: [200, 210]},
{categoryId: 3, ids: [300]} ]
*/
这是一个 fiddle如果你想尝试一下。
当我看到这个问题时,我想我想要:
- 合并所有
configs
对象,这样我就有一大组options
对象 - 按
categoryId
分组 - 然后我真的迷失了方向......我怀疑我可以在这里使用reduce(),但后来我也认为我需要一个map()来实际生成转换后的对象。
无论如何,我一直在循环这个问题,但没有取得进展,我希望有人能给我指出正确的方向。
最佳答案
使用 ES2015 语法:
_.map(
_.groupBy(_.flatMap(configs, config => config.options), 'categoryId'),
(val, key) => ({categoryId: key, ids: _.uniq(_.map(val, v => v.id)) })
)
兼容 ES5(由 Babel 生成):
_.map(
_.groupBy(
_.flatMap(configs, function (config) {
return config.options;
}),
'categoryId'),
function (val, key) {
return {
categoryId: key,
ids: _.uniq(_.map(val, function (v) {
return v.id;
}))
};
});
说明:
_.flatMap(configs, config => config.options)
从每个配置对象中获取options
数组,将它们展平为[{categoryId: xx, id: yy}, ...]
的单个数组
[ {categoryId:1,id:100},
{categoryId:2,id:200},
{categoryId:3,id:300},
{categoryId:1,id:105},
{categoryId:2,id:210},
{categoryId:2,id:200},
{categoryId:1,id:165},
{categoryId:3,id:300} ]
_.groupBy(..., 'categoryId')
按categoryId
对上面的数组进行分组,如[{xx: [categoryId: xx, id: yy}, ...]
{
1:[
{categoryId:1,id:100},
{categoryId:1,id:105},
{categoryId:1,id:165} ],
2:[
{categoryId:2,id:210},
{categoryId:2,id:200},
{categoryId:2,id:200} ],
3:[
{categoryId:3,id:300},
{categoryId:3,id:300} ] }
_.map(..., (val, key) => ({categoryId: key, ids: _.uniq(_.map(val, v => v.id)) }))
接收 val = [{xx: [categoryId: xx, id: yy}, ...]
, key: xx
并将它们映射到 的对象>categoryId
设置为接收到的 key ,ids
设置为来自分组对象的唯一 id
数组。结果就是你想要的数组。
[ {
categoryId:1,
ids:[100,105,165]},
{
categoryId:2,
ids:[200,210]},
{
categoryId:3,
ids:[300]}]
关于javascript - 使用 Lodash,如何将这些数据转换为所需的格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37737952/