2017-01-12 39 views
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。但是如果我需要commentsusers的ID。基本上我可以用Object.keys()得到它,可能是有什麼其他的方式,normalizr可以提供我們從API獲取這個數據的正常化步驟嗎?我找不到它API。或者你可以建議任何方法來做到這一點,而不是自動?因爲Object.keys()不適合我。

回答

1

由於您正在歸一化的值是article,因此來自Normalizr的result值將是該文章的ID。正如你自己所建議的,如果你需要一個不同的嵌套實體類型的ID,你將不得不使用類似Object.keys(normalizedData.entities.comments)