gpt4 book ai didi

javascript - Normalizr 可以在标准化数据上创建索引吗?

转载 作者:行者123 更新时间:2023-12-02 22:49:31 24 4
gpt4 key购买 nike

我使用 normalzr 来标准化 Redux 存储中的数据。但是,我不知道如何在标准化数据上创建标准化索引。以下是我在不使用 Normalizr 的情况下解决该问题的方法:

var postData = [
{ id: 101, pet: "dog", sleeps: "bed", likesme: "yes" },
{ id: 102, pet: "cat", sleeps: "porch", likesme: "no" },
{ id: 103, pet: "fish", sleeps: "bowl", likesme: "yes" },
{ id: 104, pet: "rock", sleeps: "porch", likesme: "yes" }
];

const indexer = (objarr, idcol, indexcol) => {

var retobj = {};
objarr.forEach((row)=>{

var index = row[indexcol];
if (retobj[index] == null)
retobj[index] = [];

retobj[index].push(row[idcol]);
});

return(retobj);
};

var bySleeps = indexer(postData,"id","sleeps");
console.log(bySleeps);

var byLikesMe = indexer(postData,"id","likesme");
console.log(byLikesMe);

产品:

{ bed: [ 101 ], porch: [ 102, 104 ], bowl: [ 103 ] }
{ yes: [ 101, 103, 104 ], no: [ 102 ] }

用法示例:

var state.petsThatLikeMe = byLikesMe["yes"];
var state.petsThatDontLikeMe = byLikesMe["no"];

最佳答案

你可以这样做,这将生成所有可能的键及其值和属于这些值的 id。

如果您会更频繁地触发此生成,则最好缓存(内存)结果,尤其是当数据集变得更大时。

console.log(likesme);

{
"yes": [
101,
103,
104
],
"no": [
102
]
}

console.log(likesme.yes);

[
101,
103,
104
]

console.log(sleeps.bed)

[
101
]

var postData = [
{ id: 101, pet: "dog", sleeps: "bed", likesme: "yes" },
{ id: 102, pet: "cat", sleeps: "porch", likesme: "no" },
{ id: 103, pet: "fish", sleeps: "bowl", likesme: "yes" },
{ id: 104, pet: "rock", sleeps: "porch", likesme: "yes" }
];

function generate(data){
return data.reduce((state, entry) => {
Object.entries(entry).forEach(([subject, value]) => {
if (subject in state) {
value in state[subject] ?
state[subject][value].push(entry.id) :
state[subject][value] = [entry.id]
} else {
if (subject !== 'id') state[subject] = {[value]: [entry.id]};
}
});
return state;
}, {});
}

const { likesme, sleeps, pet } = generate(postData)

console.log(likesme);
console.log(likesme.yes);
console.log(sleeps.bed)

关于javascript - Normalizr 可以在标准化数据上创建索引吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58241418/

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