【发布时间】:2020-02-03 02:07:20
【问题描述】:
我使用 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"];
【问题讨论】:
-
我不熟悉 normalizr。但我可以想象 id 用于规范化数据。在您的示例中,
bed并不是唯一的,因此我认为仅使用 normalizr 很难产生您当前的结果。 -
我同意。 normalizr 将创建 { '101':{ ...obj}, '102':{obj},...}。 npm 上有索引工具,但想要一个可以与 normalizr 一起使用的工具。
-
我可能有东西给你。看看我的回答,希望对你有帮助..
标签: javascript indexing normalization