1

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

4

1 に答える 1

1

正規化する値は であるため、Normalizr からarticleresult値が記事の ID になります。あなたが提案したように、別のネストされたエンティティタイプのIDが必要な場合は、次のようなものを使用する必要がありますObject.keys(normalizedData.entities.comments)

于 2017-01-12T13:54:06.447 に答える