2016-07-13 9 views
2

ノーマライザを使用してサーバーから2つの応答を正規化して店舗に保存する必要があります。 最初の応答は私にセクションを与え、2番目の応答は私にセクションを与えます。 セクションには多くの投稿があります。 1つの投稿は、の1つのセクションしか持てません。Normalizrで入れ子になっているネストされたツリーをノーマライズ

ファーストレスポンス(セクション):

[ 
    { 
    id: 10, 
    title: "foo" 
    }, 
    ... 
] 

セカンド応答(記事):

{ 
    entities: { 
    sections: { 
     10: {title: "foo", posts: [2, 5, 12, 152]}, 
     15: {title: "example", posts: [1, 8]}, 
     ... 
    }, 
    posts: { 
     1: {id: 1, sid: 15, title: "abc", text: "something"}, 
     2: {id: 2, sid: 10, title: "foo", text: "foo foo"}, 
     ... 
    } 
    } 
} 
:私はこのスキーマへの応答を正常化したい

[ 
    { 
    id: 2, 
    sid: 10, //id of the section 
    title: "foo", 
    text: "foo foo" 
    }, 
    ... 
] 

Sinc eレスポンスはネストされていません。スキーマの定義方法はわかりません。

答えて

2

あなたは簡単なコードでそれを行うことができますか?ライブラリがなければ? oO

var posts = [ ... ]; // some posts here 
var sections = [ ... ]; // some sections here 
var schema = { entities: { sections: {}, posts: {} } }; 

for (var i = 0; i < sections.length; i++) { 
    var section = sections[i]; 
    schema.entities.sections[section.id] = { 
     title: section.title, 
     posts: [] 
    } 
} 

for (var j = 0; j < posts.length; j++) { 
    var post = posts[j]; 
    schema.entities.posts[post.id] = post; 
    schema.entities.sections[post.sid].posts.push(post.id); 
} 
+1

これは良い答えです。 Normalizrは、デネストされる必要がある単一のJSONオブジェクトを処理するためのものです。あなたは最初にあなたの反応を一緒にしゃぶり、そしてnormalizrを通してそれを実行しなければなりません。この答えははるかに簡単な解決策です。 –

+0

@PaulArmstrongよく、実際には非正規化すると意味があります。私たちは残りのAPIを持っており、JSONは深くネストされていませんが、私たちは非正規化されたオブジェクトを使用します。それのためにいくつかの一般化された方法を持つことは素晴らしいことでしょう – Veikedo

関連する問題