我有从 API 返回的示例数据。
我正在使用 Lodash 的 _.groupBy
将数据转换为我可以更好地使用的对象。
返回的原始数据是这样的:
[
{
"name": "jim",
"color": "blue",
"age": "22"
},
{
"name": "Sam",
"color": "blue",
"age": "33"
},
{
"name": "eddie",
"color": "green",
"age": "77"
}
]
我希望 _.groupBy
函数返回一个如下所示的对象:
[
{
color: "blue",
users: [
{
"name": "jim",
"color": "blue",
"age": "22"
},
{
"name": "Sam",
"color": "blue",
"age": "33"
}
]
},
{
color: "green",
users: [
{
"name": "eddie",
"color": "green",
"age": "77"
}
]
}
]
目前我正在使用
_.groupBy(a, function(b) { return b.color})
返回这个。
{blue: [{..}], green: [{...}]}
分组是正确的,但我真的很想添加我想要的键(color
、users
)。这可能使用 _.groupBy
吗?还是其他一些 LoDash
实用程序?
最佳答案
您可以在 Underscore 和 Lodash(3.x 和 4.x)中这样做。
var data = [{
"name": "jim",
"color": "blue",
"age": "22"
}, {
"name": "Sam",
"color": "blue",
"age": "33"
}, {
"name": "eddie",
"color": "green",
"age": "77"
}];
console.log(
_.chain(data)
// Group the elements of Array based on `color` property
.groupBy("color")
// `key` is group's name (color), `value` is the array of objects
.map((value, key) => ({ color: key, users: value }))
.value()
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
原始答案
var result = _.chain(data)
.groupBy("color")
.pairs()
.map(function(currentItem) {
return _.object(_.zip(["color", "users"], currentItem));
})
.value();
console.log(result);
注意:从Lodash 4.0 开始,.pairs
函数已重命名为_.toPairs()
。
关于javascript - 使用 lodash .groupBy。如何为分组输出添加自己的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23600897/