比较和合并两个对象数组

时间:2017-03-12 18:28:26

标签: javascript

我有两个对象数组(arr1和arr2)。我想从arr1中选择对象,其中arr1.id == arr2.typeId并添加到结果arr2.Price

#include <stdio.h>
#include <string.h>

typedef struct batch
{
  int month;
  int day;
  int qty;
  float item_cost;
  int batch_num;
} BATCH;

struct stock
{
  char item_name[50];
  int t_qty;
  float t_item_cost;
  int item_code;
  BATCH batch[10];
  int last_batch_num;
  float price_for_one;
  float price;
};

int main()
{
   FILE *filepointer;
   filepointer = fopen("stocklist.txt", "r+");

   struct stock loop;

   while(fread(&loop, sizeof(struct stock), 1, filepointer))
   {
       printf("%s\n", loop.item_name);
       strcpy(loop.item_name, "Jerb");
       printf("%s\n", loop.item_name);

       fwrite(&loop, sizeof(struct stock), 1, filepointer);
    }
}

我如何获得以下内容?

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

3 个答案:

答案 0 :(得分:2)

您可以在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)

答案 1 :(得分:2)

您可以创建一个没有任何带Object.create原型的对象作为哈希表,只有当两个数组都有一个公共ID时才推送新对象。

&#13;
&#13;
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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 2 :(得分:1)

另一种方法,使用Array#forEach

&#13;
&#13;
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
&#13;
&#13;
&#13;