[英]How to filter normalized nested JSON data with no array?
使用normalizr
庫后,我的應用程序的Redux狀態具有以下標准化的JSON對象結果:
{
sports: {
byId: {
1: {
id: 1,
name: 'Soccer',
slug: 'soccer'
},
2: {
id: 2,
name: 'Basketball',
slug: 'basketball'
},
3: {
id: 3,
name: 'American Football',
slug: 'american-football'
}
},
allIds: [
'1',
'2',
'3'
]
},
competitions: {
byId: {
'1': {
id: 1,
name: 'Competition 1',
short_name: 'Comp 1',
slug: 'comp-1',
sport: 1,
status: {
is_live: false
}
},
'2': {
id: 2,
name: 'Competition 2',
short_name: 'Comp 2',
slug: 'comp-2',
sport: 1,
status: {
is_live: true
}
},
'3': {
id: 3,
name: 'National Basketball League',
short_name: 'NBA',
slug: 'national-basketball-league',
sport_slug: 'basketball',
sport: 3,
status: {
is_live: true
}
}
},
allIds: [
'1',
'2',
'3'
]
}
我想要實現的目標:我想要一個按sports
篩選/分類的competitions
列表。
我怎樣才能做到這一點?
我也希望能夠通過status.is_live
對competitions
進行status.is_live
。
那么,怎樣才能讓我的列表competitions
被擊穿sport
是status.is_live
等於真實competitions
status.is_live
等於假的?
任何幫助表示贊賞! 謝謝
如果您不想使用lodash ,可以很容易地編寫一個.groupBy
函數( 例如 )。 您需要遍歷輸出對象,並使用for而不是.mapValues
來重新分配其子級值。
我在示例中使用了lodash,只是為了指出邏輯。
注意:我將刪除原始響應中的數據分組,然后讓客戶端自行執行操作-在未排序的數組和過濾器/映射上進行操作比在具有冗余對象的值上進行處理更容易鍵(因為它們按ID表示組)
let data = { sports: { byId: { 1: { id: 1, name: 'Soccer', slug: 'soccer' }, 2: { id: 2, name: 'Basketball', slug: 'basketball' }, 3: { id: 3, name: 'American Football', slug: 'american-football' } }, allIds: [ '1', '2', '3' ] }, competitions: { byId: { '1': { id: 1, name: 'Competition 1', short_name: 'Comp 1', slug: 'comp-1', sport: 1, status: { is_live: false } }, '2': { id: 2, name: 'Competition 2', short_name: 'Comp 2', slug: 'comp-2', sport: 1, status: { is_live: true } }, '3': { id: 3, name: 'National Basketball League', short_name: 'NBA', slug: 'national-basketball-league', sport_slug: 'basketball', sport: 3, status: { is_live: true } } }, allIds: [ '1', '2', '3' ] } } let competitions = Object.values(data.competitions.byId) // _.chain(arr) keeps returning `lodash` objects // so I don't have to call it separately for every action let filteredCompetitions = _.chain(competitions) .groupBy(i => i.status.is_live) .mapValues(i => _.groupBy(i, 'sport')) .value() // returns the final value console.log(filteredCompetitions)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.