2017-03-12 18 views
0

私は2つのオブジェクトの配列(arr1とarr2)を持っています。私はARR1 arr1.id == arr2.typeIdからオブジェクトを選択し、2つのオブジェクトの配列の比較とマージ

var arr1 = 
[{"id":20,"name":"name1"}, 
{"id":24,"name":"name2"}, 
{"id":25,"name":"name3"}, 
{"id":28,"name":"name4"}, 
{"id":29,"name":"name5"}] 


var arr2 = 
[{"typeId":20,"Price":500}, 
{"typeId":24,"Price":1100}, 
{"typeId":28,"Price":1000}] 

がどのように私は次のことを得ることができますarr2.Price結果に追加したいですか?

var result = 
[{"item":{"id":20,"name":"name1"}, "price":"500"}}, 
{{"item":{"id":24,"name":"name2"}, "price":"1100"}, 
{{"item":{"id":28,"name":"name4"}, "price":"1000"}] 


var result = arr1.filter(function(obj1){ 
         return arr2.some(function(obj2){ 
          return obj1.id === obj2.typeId; 
         }); 
        }) 
+0

用途に応じて(http://stackoverflow.com/questions/7146217/merge-2-arrays-of-objects)オブジェクトの2つの配列をマージ] –

答えて

2

あなたはARR2にreduce()を使用して、同じIDを持つオブジェクトがfind()とARR1に存在するかどうかを確認することができます。 Array#forEachを用い

var arr1 = 
 
[{"id":20,"name":"name1"}, 
 
{"id":24,"name":"name2"}, 
 
{"id":25,"name":"name3"}, 
 
{"id":28,"name":"name4"}, 
 
{"id":29,"name":"name5"}] 
 

 
var arr2 = 
 
[{"typeId":20,"Price":500}, 
 
{"typeId":24,"Price":1100}, 
 
{"typeId":28,"Price":1000}] 
 

 
var result = arr2.reduce(function(r, e) { 
 
    var c = arr1.find(a => e.typeId == a.id) 
 
    if(c) r.push({item: c, price: e.Price}) 
 
    return r 
 
}, []) 
 

 
console.log(result)

+0

の可能性のある重複OPの場合( 'if'文が常にtrueの場合)、' reduce'の代わりに 'map'を使用することができます。しかしながら、O(n^2)の複雑さは改善される可能性がある。 – 4castle

+0

@ 4castleその 'arr2.map(e =>(item = arr1.find(a => e.typeId == a.id)、price:e.Price}))')に追加するには、私たちはそれを仮定できると思う。一致するものが見つからない場合のデフォルト値の例もここにあります。https://jsfiddle.net/Lg0wyt9u/1686/ –

1

別のアプローチ、。

var arr1 = [{id:20,name:"name1"},{id:24,name:"name2"},{id:25,name:"name3"},{id:28,name:"name4"},{id:29,name:"name5"}], 
 
    arr2 = [{typeId:20,Price:500},{typeId:24,Price:1100},{typeId:28,Price:1e3}], 
 
    result = []; 
 
    
 
    arr2.forEach(function(v){ 
 
     var elem = arr1.find(c => c.id == v.typeId); //find corresponding element from the `arr1` array 
 
     result.push({item: elem, price: v.Price}); //push an object containing `item` and `price` keys into the result array 
 
    }); 
 

 
    console.log(result); //reveal the result

2

あなたは両方の配列が共通のIDを持っている場合にのみ、ハッシュテーブルとしてObject.createで任意のプロトタイプせずにオブジェクトを作成し、新しいオブジェクトをプッシュすることができます。

var arr1 = [{ id: 20, name: "name1" }, { id: 24, name: "name2" }, { id: 25, name: "name3" }, { id: 28, name: "name4" }, { id: 29, name: "name5" }], 
 
    arr2 = [{ typeId: 20, Price: 500 }, { typeId: 24, Price: 1100 }, { typeId: 28, Price: 1000 }], 
 
    hash = Object.create(null), 
 
    result = []; 
 

 
arr1.forEach(function (a) { 
 
    hash[a.id] = a; 
 
}); 
 

 
arr2.forEach(function (a) { 
 
    if (hash[a.typeId]) { 
 
     result.push({ item: hash[a.typeId], price: a.Price }); 
 
    } 
 
}); 
 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

関連する問題