gpt4 book ai didi

javascript - 带有嵌套对象数组的 Normalizr

转载 作者:行者123 更新时间:2023-12-03 08:29:10 24 4
gpt4 key购买 nike

我有一个像这样的嵌套对象数组:

var matchs = [
{
id: 10689,
sport: 'Tennis',
players: [
{
id: 22,
name:'Rafa Nadal',
country: 'Spain',
odds: [
{id: 1, bookie_1: 1.60},
{id: 2, bookie_2: 1.61},
{id: 3, bookie_3: 1.62},
]
},
{
id: 23,
name:'Roger Federer',
country: 'Spain',
odds: [
{id: 4, bookie_1: 2.60},
{id: 5, bookie_2: 2.61},
{id: 6, bookie_3: 2.62},
]
}
]
},
{
id: 12389,
sport: 'Tennis',
players: [
{
id: 45,
name:'Fernando Verdasco',
country: 'Spain',
odds: [
{id: 7, bookie_1: 2.60},
{id: 8, bookie_2: 2.61},
{id: 9, bookie_3: 2.62},
]
},
{
id: 65,
name:'Andy Murray',
country: 'Spain',
odds: [
{id: 10, bookie_1: 1.60},
{id: 11, bookie_2: 1.61},
{id: 12, bookie_3: 1.62},
]
}
]
}
];

我想使用 normalizr 来简化数组并与 redux 一起使用。我已经阅读了 Normalizr 文档,但它的示例很少,而且我不知道我做错了什么。

我已经尝试了以下代码但没有成功。我得到的结果是一个未定义的数组。

  import { normalize, schema } from 'normalizr';   

const match = new schema.Entity('matchs');
const player = new schema.Entity('players');
const odd = new schema.Entity('odds');

match.define({
player: [player],
odd: [odd]
});

console.log(normalize(matchs, [match]));

我需要这样的东西:

{
result: "123",
entities: {
"matchs": {
"123": {
id: "123",
players: [ "1","2" ],
odds: [ "1", "2" ]
}
},
"players": {
"1": { "id": "1", "name": "Rafa Nadal" },
"2": { "id": "2", "name": "Andy Murray" }
},
"odds": {
"1": { id: "1", "bookie_1": "1.20" }
"2": { id: "2", "bookie_2": "1.21" }
"3": { id: "3", "bookie_3": "1.22" }
}
}
}

最佳答案

我找不到仅使用 normalizr 的直接解决方案,所以我唯一的选择是在传递给 normalizer 之前预先格式化数据。

const preformattedData = data.map(sport => {
const oddArrays = sport.players.map(player => player.odds || []);
return {
...sport,
odds: [].concat.apply([], oddArrays)
}
})

const odd = new schema.Entity('odds')
const player = new schema.Entity('players',
{
odds: [ odd ]
}
)
const sport = new schema.Entity('sports',
{
players: [ player ],
odds: [odd]
}
)

const normalizedData = normalize(preformattedData, [ sport ]);

演示:https://codesandbox.io/s/20onxowzwn

关于javascript - 带有嵌套对象数组的 Normalizr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47794469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com