簡體   English   中英

比較和合並兩個對象數組

[英]Comparing and merging two arrays of objects

我有兩個對象數組(arr1和arr2)。 我想從arr1中選擇對象,其中arr1.id == arr2.typeId並添加到結果arr2.Price

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 = 
[{"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;
                        });
                    })

您可以在arr2上使用reduce() ,然后使用find()檢查arr1中是否存在具有相同ID的對象。

 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) 

您可以使用Object.create作為哈希表來創建沒有任何原型的對象,並僅在兩個數組具有相同的ID時才推送新對象。

 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; } 

另一種方法,使用Array#forEach

 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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM