如何在javascript中将多个数组合并为单个数组

时间:2018-11-29 09:03:53

标签: javascript arrays merge combinations multiple-columns

我有多个数组,其中有多种数据类型,例如:

 var student= [{
      id : 1,
      name : 'name1',
      year: 2016,
      dist_id: 251,
      zone_id: 25106
    },
    {
      id : 1,
      name : 'name2',
      year: 2018,
      dist_id: 252,
      zone_id: 25212
    },];

    var dist= [{
        id : 251,
        name : 'dist1'
    },
    {
       id : 252,
        name : 'dist2'
    }];
    var zone= [{
        id : 25106,
        name : 'zone1'
    },
    {
       id : 25212,
        name : 'zone2'
    }];

我想创建一个将所有数据组合为一个数组,以便数组中的字段如下所示:

var merge = [{
  id: 1,
  name : 'name1',
  year: 2016,
  distname : 'dist1',
  zonename: 'zone1',
},
{
  id: 2,
  name : 'name2',
  year: 2018,
  distname : 'dist2',
  zonename: 'zone2',
}];

先谢谢了。

2 个答案:

答案 0 :(得分:2)

您可以使用Map作为距离和区域,并将值映射到新对象中。

var student = [{ id: 1, name: 'name1', year: 2016, dist_id: 251, zone_id: 25106 }, { id: 1, name: 'name2', year: 2018, dist_id: 252, zone_id: 25212 }],
    dist = [{ id: 251, name: 'dist1' }, { id: 252, name: 'dist2' }],
    zone = [{ id: 25106, name: 'zone1' }, { id: 25212, name: 'zone2' }],
    distMap = new Map(dist.map(({ id, name: distname }) => [id, { distname }])),
    zoneMap = new Map(zone.map(({ id, name: zonename }) => [id, { zonename }])),
    merged = student.map(({ id, name, year, dist_id, zone_id }) => Object.assign(
        { id, name, year },
        distMap.get(dist_id),
        zoneMap.get(zone_id)
    ));

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

答案 1 :(得分:1)

您可以将map()数组student到所需的merge数组中,对于每次映射迭代,您都将在distzone数组中搜索分别在dist_idzone_id上匹配的项目,并将的name合并到映射结果中:

var student= [
{ id : 1, name : 'name1', year: 2016, dist_id: 251, zone_id: 25106 }, 
{ id : 1, name : 'name2', year: 2018, dist_id: 252, zone_id: 25212 } ];

var dist= [
{ id : 251, name : 'dist1' }, { id : 252, name : 'dist2' }];

var zone= [ 
{ id : 25106, name : 'zone1' }, { id : 25212, name : 'zone2' } ];
    
// Perform a mapping over the student array to aquire merge array in required
// format, with required distname/zonename data
var merge = student.map((s) => {
  
  // Search dist and zone arrays for items that match of dist_id/zone_id
  // by filtering and mapping these arrays to find distname and zonename
  // for this student
  const distname = dist.filter(d => d.id === s.dist_id).map(d => d.name)[0];
  const zonename = zone.filter(z => z.id === s.zone_id).map(z => z.name)[0];
  
  return {
    id : s.id,
    name : s.name,
    year : s.year,
    distname : distname,
    zonename : zonename
  }

});

console.log('required merge array:', merge)