2016-05-27 12 views
0

jQueryを使用して次の2つの配列をchild_array.cat_parent_id == parent_array.cat_idにマージするにはどうすればよいですか?一致するオブジェクト値に基づいてある配列から別の配列にオブジェクトをマージする

parent_array:

[{ 
    "cat_name" : "Fruit", 
    "cat_id" : 77 
}, { 
    "cat_name" : "Vegetables", 
    "cat_id" : 221 
}] 

そして、私はparent_arrayにマージしているしたいと思いchild_array:

[{ 
    "cat_name" : "Bananas", 
    "cat_id" : 79, 
    "cat_parent_id" : 77 
},{ 
    "cat_name" : "Apples", 
    "cat_id" : 80, 
    "cat_parent_id" : 77 
}, { 
    "cat_name" : "Carrots", 
    "cat_id" : 222, 
    "cat_parent_id" : 221 
}] 

は、ここで私は、出力は次のようになりたいものです。

[{ 
    "cat_name" : "Fruit", 
    "cat_id" : 77, 
    "cat_children": [ 
    { 
     "cat_name" : "Bananas", 
     "cat_id" : 79 
    }, 
    { 
     "cat_name" : "Apples", 
     "cat_id" : 80 
    } 
    ] 
}, { 
    "cat_name" : "Vegetables", 
    "cat_id" : 221, 
    "cat_children": [ 
    { 
     "cat_name" : "Carrots", 
     "cat_id" : 222 
    } 
    ] 
}] 
+0

は、あなたがこの問題を解決するために何かをしようとしたことがありますか?解決策のどの部分を執着していますか? –

+1

ネストされたループがそれを行う必要があります。親配列をキーがカテゴリIDであるオブジェクトに変換した方が簡単です。 – Barmar

答えて

0

これを行うために必ずしもjQueryが必要なわけではありません...ネストされたループを作成してチェックしますs。あなたのJSONの構造を大幅にこれを達成するために最適化することができますが、次の関数はそれをそれが道を達成する:

function merge(_parent,_children){ 
    var result = _parent; 
    for(x in _children){ 
    var parentID = _children[x].cat_parent_id; 
    for(y in _parent){ 
     if(_parent[y].cat_id == parentID){  
     if(!result[y].cat_children){ 
      result[y].cat_children = []; 
     } 
     result[y].cat_children.push(_children[x]); 
     } 
    } 
    } 
    return result; 
} 
+0

ありがとうございます - 素敵で簡単です。 forループを 'for(var x = 0; x <_children.length; x ++)'形式に変更して、子オブジェクトが重複しないようにしなければなりませんでした。 – Troy

+0

うれしかった!オブジェクトキーを変更する場合に備えて、これを完全に動的にする方法もありますが、この特定のアプリケーションでは、それは良いことです。 –

関連する問題