たとえば、次のような単純な 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"
}
}
]
}
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 のみを取得します。しかし、 または の ID が必要な場合はどうすればよいでしょうcomments
かusers
。基本的に私はそれを得ることができObject.keys()
ます.他の方法があるかもしれません.normalizrはAPIから提供して正規化の段階でこのデータを取得できますか? APIについては何も見つかりません。または、自動的にではなく、それを行う方法を提案できますか? Object.keys()
私には似合わないからです。