返回结果中嵌套规范化数据的ID列表

时间:2017-01-12 09:29:29

标签: javascript json normalization normalize normalizr

例如,我有一个简单的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"
      }
    }
  ]
}

使用normalizrexample

中的模式进行规范化后
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()不适合我。

1 个答案:

答案 0 :(得分:1)

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

之类的内容。