【发布时间】:2017-05-27 08:08:31
【问题描述】:
例如我有一个简单的 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"
}
}
]
}
在使用 normalizr 和来自 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);
我会得到这个标准化的 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() 不适合我。
【问题讨论】:
标签: javascript json normalization normalize normalizr