1
比如我有一個簡單的JSON,像這樣的列表:返回的ID在結果嵌套標準化數據
{
"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"
}
}
]
}
而且從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);
與normalizr和模式正常化後,我會得到這個規範化的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。但是如果我需要comments
或users
的ID。基本上我可以用Object.keys()
得到它,可能是有什麼其他的方式,normalizr可以提供我們從API獲取這個數據的正常化步驟嗎?我找不到它API。或者你可以建議任何方法來做到這一點,而不是自動?因爲Object.keys()
不適合我。