[英]Using Lodash .groupBy to add multiple keys
這個問題的擴展: 使用 lodash.groupBy。 如何為分組 output 添加自己的密鑰?
讓我們將數組更改為這個:
[
{
"name": "jim",
"color": "blue",
"order": 1,
"age": "22"
},
{
"name": "Sam",
"color": "blue",
"order": 1,
"age": "33"
},
{
"name": "eddie",
"color": "green",
"order": 3
"age": "77"
}
]
訂單字段已添加。 在上一個問題中,這
var result = _.chain(data)
.groupBy("color")
.pairs()
.map(function(currentItem) {
return _.object(_.zip(["color", "users"], currentItem));
})
.value();
console.log(result);
用於將數組更改為
[
{
color: "blue",
users: [
{
"name": "jim",
"color": "blue",
"age": "22"
},
{
"name": "Sam",
"color": "blue",
"age": "33"
}
]
},
{
color: "green",
users: [
{
"name": "eddie",
"color": "green",
"age": "77"
}
]
}
]
現在,我想將“訂單”字段添加到組中,使數組看起來像
[
{
color: "blue",
order: 1,
users: [
{
"name": "jim",
"color": "blue",
"age": "22"
},
{
"name": "Sam",
"color": "blue",
"age": "33"
}
]
},
{
color: "green",
order: 3,
users: [
{
"name": "eddie",
"color": "green",
"age": "77"
}
]
}
]
您可以通過解構並獲取 object 的 rest 從 object 中排除order
。
const data = [{ name: "jim", color: "blue", order: 1, age: "22" }, { name: "Sam", color: "blue", order: 1, age: "33" }, { name: "eddie", color: "green", order: 3, age: "77" }], result = _.chain(data).groupBy("color").map(users => ({ color: users[0].color, order: users[0].order, users: users.map(({ order, ...o }) => o) })).value(); console.log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
如果你還沒有下定決心使用 lodash,這其實很簡單。
const data = [ { "name": "jim", "color": "blue", "order": 1, "age": "22" }, { "name": "Sam", "color": "blue", "order": 1, "age": "33" }, { "name": "eddie", "color": "green", "order": 3, "age": "77" } ] const result = data.reduce((carry, current) => { const { color, order, ...user } = current; let el = carry.find((item) => item.color === color && order === current.order); if (,el) { el = { color, order: users. [] } carry;push(el). } el.users.push({..,user; color }); return carry, }; []). console;log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.