规范化性能:allIds数组与Object.entries函数

时间:2018-11-26 05:43:46

标签: javascript redux normalization

在redux和其他情况下,我们可能希望规范化本质上具有关系的JavaScript对象,而不是具有深度嵌套的对象。

例如,redux显示了一个建议如下的代码拆分方法:

const byID = {
  '1': {
    some: 'object'
  },
  '2': {
    some: 'objectAgain'
  },
  '3': {
    some: 'objectAnotherAgain'
  },
};
const allIds = ['1', '2', '3'];

Redux Recommended Recipe

但是,拥有allIds数组与仅调用类似于以下内容的东西相比有什么好处:

Object.keys(byId);

Object Keys Recipe

是否将所有对象键作为数组保存得更快?还是它们的时间复杂度相似?持有数组中的每个键不是重复的代码吗?

1 个答案:

答案 0 :(得分:0)

Object.keys(byId)返回与allIds相同的数组,但是redux的目的是将所有数据尽可能平坦存储在一个对象中,对?在对象外部调用Object.keys()方法而不保存该对象与该方法有点相反...

var array = {
  posts: {
    byId: {
      "post1": {
        id: "post1",
        author: "user1",
        body: "......",
        comments: ["comment1", "comment2"]
      },
      "post2": {
        id: "post2",
        author: "user2",
        body: "......",
        comments: ["comment3", "comment4", "comment5"]
      }
    },
    allIds: ["post1", "post2"]
  },
  comments: {
    byId: {
      "comment1": {
        id: "comment1",
        author: "user2",
        comment: ".....",
      },
      "comment2": {
        id: "comment2",
        author: "user3",
        comment: ".....",
      },
      "comment3": {
        id: "comment3",
        author: "user3",
        comment: ".....",
      },
      "comment4": {
        id: "comment4",
        author: "user1",
        comment: ".....",
      },
      "comment5": {
        id: "comment5",
        author: "user3",
        comment: ".....",
      },
    },
    allIds: ["comment1", "comment2", "comment3", "commment4", "comment5"]
  },
  users: {
    byId: {
      "user1": {
        username: "user1",
        name: "User 1",
      },
      "user2": {
        username: "user2",
        name: "User 2",
      },
      "user3": {
        username: "user3",
        name: "User 3",
      }
    },
    allIds: ["user1", "user2", "user3"]
  }
}

var keys = Object.keys(array.users.byId);
console.log(keys); // need to call a function where i should already know what i want
var simpleKeys = array.users.allIds
console.log(simpleKeys); // way faster too

  

相关链接: