![](/img/trans.png)
[英]Flatten an array of objects and get unique keys and values by a repeated date with Lodash?
[英]Lodash: How to get unique values from an object array and then sort those objects by those unique values?
我正在嘗試使用Lodash從對象數組中獲取唯一值,然后使用這些值作為鍵來對對象數組進行排序。 我能夠找到解決方案,但是我不確定它是最復雜,可讀或性能最高的方式。
使用_.uniq
和_.map
,我能夠從每個artist
獲得唯一的country
值。 然后我循環了這些價值觀,並由他們過濾artists
。
let artists = [
{ name: "Bob Jones", country: "Australia"},
{ name: "Jane Smith", country: "Australia"},
{ name: "James Good", country: "USA"},
{ name: "Jeremy Bond", country: "Japan"},
]
let countries = _.uniq(_.map(artists, 'country'))
// ["Australia", "USA", "Japan"]
let res = []
for (let i = 0; i < countries.length; i++) {
let country = countries[i]
let obj = {
country: country,
artists: artists.filter(artist => artist.country === country)
}
res.push(obj)
}
console.log(res)
/* [
{ country: "Australia",
artists: [
{ name: "Bob Jones", country: "Australia"},
{ name: "Jane Smith", country: "Australia"}
]
},
{ country: "USA",
artists: [
{ name: "James Good", country: "USA"}
]
},
{ country: "Japan",
artists: [
{ name: "Jeremy Bond", country: "Japan"}
]
}
]
*/
是否有任何Lodash功能可以代替for循環和對象分配?
使用_.groupBy()
將藝術家收集到{ [country]: artists }
的對象,然后使用_.map()
將對象轉換為數組:
const artists = [ { name: "Bob Jones", country: "Australia"}, { name: "Jane Smith", country: "Australia"}, { name: "James Good", country: "USA"}, { name: "Jeremy Bond", country: "Japan"}, ] const result = _.map( _.groupBy(artists, 'country'), (artists, country) => ({ country, artists }) ) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
與lodash / fp相同的解決方案 - 使用_.flow()
生成一個函數:
const { flow, groupBy, map, head } = _ const byCountry = flow( groupBy('country'), map(artists => ({ country: head(artists).country, artists })) ) const artists = [ { name: "Bob Jones", country: "Australia"}, { name: "Jane Smith", country: "Australia"}, { name: "James Good", country: "USA"}, { name: "Jeremy Bond", country: "Japan"}, ] const result = byCountry(artists) console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.