For example I have a simple JSON, like this:
例如,我有一个简单的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"
}
}
]
}
And after normalizing with normalizr and schemas from example
在使用示例中的normalizr和schema进行规范化之后
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:
我会得到这个规范化的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.
在normalizedData.result中,我只会获得文章ID。但是,如果我需要评论ID或用户,该怎么办?基本上我可以用Object.keys()来获取它,可能还有其他方法,normalizr可以从API提供我们在规范化步骤中获取这些数据吗? API无法找到任何关于它的信息。或者你可以建议任何方法来做,而不是自动?因为Object.keys()看起来不适合我。
1 个解决方案
#1
1
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)
由于您正在规范化的值是一篇文章,因此Normalizr的结果值将是文章的ID。正如你自己建议的那样,如果你需要一个不同的嵌套实体类型的ID,你将不得不使用像Object.keys(normalizedData.entities.comments)这样的东西。
#1
1
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)
由于您正在规范化的值是一篇文章,因此Normalizr的结果值将是文章的ID。正如你自己建议的那样,如果你需要一个不同的嵌套实体类型的ID,你将不得不使用像Object.keys(normalizedData.entities.comments)这样的东西。