normalizr可以在规范化数据上创建索引吗?

时间:2019-10-04 18:16:07

标签: javascript indexing normalization

我使用normalzr标准化Redux存储中的数据。但是,我不知道如何在标准化数据上创建标准化索引。这是我不使用normalizr即可解决的方法:

std::string

产生:

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 ] }

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作,这将生成所有可能的键及其值和属于这些值的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)