[英]Sorting an array of objects with lodash: not working
我有一個看起來像這樣的數組(它有更多的對象,但結構是相同的):
[
{
especiality: "surgery",
users: [
{
id: "182",
country: "Colombia",
province: "Bogota",
telephone: "211112212",
neighbourhood: "La Santa"
region: "South",
},
{
id: "182",
country: "Venezuela",
province: "Caracas",
telephone: "322323333",
region: "North",
},
{
id: "183",
country: "Brasil",
telephone: "23232333",
neighbourhood: "Santos"
region: "South",
},
]
},
如果 ID 相同,我希望地址組成一個數組(我需要映射這些元素)。 前景應該是這樣的:
user: [{id: 182, locations[(if they exist)
country: "Colombia",
province: "Bogota",
telephone: "211112212",
neighbourhood: "La Santa"
region: "South"], [country: "Venezuela",
province: "Caracas",
telephone: "322323333",
region: "North"],}]
我目前正在嘗試這個,但它根本不起作用:
getGroups = test => {
_.chain(test)
.groupBy("id")
.toPairs()
.map(item => _.zipObject(["id", "country", "province", "neighbourhood", "region"], item))
.value();
return test
}
我做錯了什么,我如何解釋可能並非在所有對象中都可用的值?
按id
對項目進行分組后,映射組,並創建一個以id
為對象的對象,該組的項目為locations
。 映射位置,並使用_.omit()
從中刪除id
。
我不確定您想如何處理外部數組。 我使用_.flatMap()
來獲取單個用戶數組,但是如果您需要維護原始結構,則有一個注釋選項。
getGroups = test => _(test) .groupBy("id") .map((locations, id) => ({ id, locations: _.map(locations, l => _.omit(l, 'id')) })) .value(); const data = [{"especiality":"surgery","users":[{"id":"182","country":"Colombia","province":"Bogota","telephone":"211112212","neighbourhood":"La Santa","region":"South"},{"id":"182","country":"Venezuela","province":"Caracas","telephone":"322323333","region":"North"},{"id":"183","country":"Brasil","telephone":"23232333","neighbourhood":"Santos","region":"South"}]}]; const result = _.flatMap(data, ({ users }) => getGroups(users)); /** maintains the original structure const result = _.map(data, ({ users, ...rest }) => ({ ...rest, users: getGroups(users) })); **/ console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.