【问题标题】:Return IDs list of nested normalized data in result返回结果中嵌套规范化数据的 ID 列表
【发布时间】:2017-05-27 08:08:31
【问题描述】:

例如我有一个简单的 JSON,像这样:

{
  "id": "123",
  "author": {
    "id": "1",
    "name": "Paul"
  },
  "title": "My awesome blog post",
  "comments": [
    {
      "id": "324",
      "commenter": {
        "id": "2",
        "name": "Nicole"
      }
    },
    {
      "id": "325",
      "commenter": {
        "id": "3",
        "name": "Alex"
      }
    }
  ]
}

在使用 normalizr 和来自 example 的模式进行规范化之后

import { normalize, schema } from 'normalizr';

// Define a users schema
const user = new schema.Entity('users');

// Define your comments schema
const comment = new schema.Entity('comments', {
  commenter: user
});

// Define your article 
const article = new schema.Entity('articles', { 
  author: user,
  comments: [ comment ]
});

const normalizedData = normalize(originalData, article);

我会得到这个标准化的 JSON:

{
  result: "123",
  entities: {
    "articles": { 
      "123": { 
        id: "123",
        author: "1",
        title: "My awesome blog post",
        comments: [ "324", "325" ]
      }
    },
    "users": {
      "1": { "id": "1", "name": "Paul" },
      "2": { "id": "2", "name": "Nicole" },
      "3": { "id": "3", "name": "Alex" }
    },
    "comments": {
      "324": { id: "324", "commenter": "2" },
      "325": { id: "325", "commenter": "3" }
    }
  }
}

normalizedData.result 中,我只会获得文章 ID。但是如果我需要commentsusers 的ID 怎么办。基本上我可以用Object.keys() 得到它,可能有没有其他方法,normalizr 可以从 API 提供我们在标准化步骤中获取这些数据?我找不到任何关于它的信息API。或者你能建议任何方法来做到这一点,而不是自动?因为Object.keys() 不适合我。

【问题讨论】:

    标签: javascript json normalization normalize normalizr


    【解决方案1】:

    由于您要规范化的值是 article,因此来自 Normalizr 的 result 值将是文章的 ID。正如您自己建议的那样,如果您需要不同的嵌套实体类型的 ID,则必须使用类似 Object.keys(normalizedData.entities.comments)

    【讨论】:

      猜你喜欢
      • 2018-05-23
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      • 2019-02-28
      • 2016-06-09
      相关资源
      最近更新 更多