AleshaOleg
AleshaOleg

Reputation: 2211

Return IDs list of nested normalized data in result

For example I have a simple JSON, like this:

{
  "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"
      }
    }
  ]
}

And after normalizing with normalizr and schemas from 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);

I will get this normalized 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" }
    }
  }
}

In normalizedData.result, I will get only articles IDs. But what if I need IDs of comments or users. Basically I can get it with Object.keys(), may be is there any other way, normalizr can provide us from API to get this data at step of normalization? I can't find anything about it it API. Or can you suggest any methods to do it, not automatically? Because Object.keys() not looks good for me.

Upvotes: 1

Views: 613

Answers (1)

Paul Armstrong
Paul Armstrong

Reputation: 7156

Since the value you're normalizing is an article, the result value from Normalizr will be the Article's ID. As you suggested yourself, if you need to the IDs of a different, nested entity type, you'll have to use something like Object.keys(normalizedData.entities.comments)

Upvotes: 1

Related Questions