比较,使用javascript(angularjs)根据数组结构映射两个数组

时间:2018-04-20 06:11:39

标签: javascript arrays array.prototype.map

我有两个阵列

array1=[["1","4",6"],["9",4","1"],["8","9","0","4","6"],["3","5","6","1"],["0"]]

array2=[{offId:"1",offName:"one"},{offId:"5",offName:"five"},{offId:"0",offName:"zero"},{offId:"9",offName:"Nine"},{offId:"3",offName:"three"}]

我需要一个结果数组为格式

result=[[{offId:"1",offName:"one"},{offId:"4",offName:""},{offId:"6",offName:""}],[{offId:"9",offName:"Nine"},{offId:"4",offName:""},{offId:"1",offName:"one"}],[{offId:"8",offName:""},{offId:"9",offName:"Nine"},{offId:"0",offName:"Zero"},{offId:"4",offName:""},{offId:"6",offName:""}],[{offId:"3",offName:"three"},{offId:"5",offName:"five"},{offId:"6",offName:""},{offId:"1",offName:"one"}],[{offId:"0",offName:"Zero"}]]

我将如何实现这一目标(数组的长度可以相同或不同)

2 个答案:

答案 0 :(得分:0)

首先使用offId

创建reduce地图
var map = array2.reduce( (a,c) => (a[c.offId] = c.offName, a), {})

现在使用map来迭代array1并使用map

返回一个对象
var result = array1.map( s => s.map( t => ({ offId : t, offName : (map[t] || "") }) ) )

<强>演示

var array1=[["1","4","6"],["9","4","1"],["8","9","0","4","6"],["3","5","6","1"],["0"]];

var array2=[{offId:"1",offName:"one"},{offId:"5",offName:"five"},{offId:"0",offName:"zero"},{offId:"9",offName:"Nine"},{offId:"3",offName:"three"}];

var map = array2.reduce( (a,c) => (a[c.offId] = c.offName, a), {});

var output = array1.map( s => s.map( t => ({ offId : t, offName : (map[t] || "") }) ) );

console.log(output);

答案 1 :(得分:0)

您可以使用Map并使用存储的对象或新对象。

var array1 = [["1", "4", "6"], ["9", "4", "1"], ["8", "9", "0", "4", "6"], ["3", "5", "6", "1"], ["0"]],
    array2 = [{ offId: "1", offName: "one" }, { offId: "5", offName: "five" }, { offId: "0", offName: "zero" }, { offId: "9", offName: "Nine" }, { offId: "3", offName: "three" }]
    map = array2.reduce((m, o) => m.set(o.offId, o), new Map),
    result = array1.map(
        a => a.map(offId => map.get(offId) || { offId, offname: '' })
    );

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