我有两个阵列
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"}]]
我将如何实现这一目标(数组的长度可以相同或不同)
答案 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; }