我有这个数组,其第一列为id:
var mainarray = [
["1001","P6","P8"],
["1002","P7"],
["1003","P7","P8","P10"],
["1004","P6","P10"],
];
我想用下面的'lookup'数组中的相应动物替换每个'P'元素:
var arraylookup= [
["P6","dog"],
["P7","cat"],
["P8","mouse"],
["P9","horse"],
["P10","cow"],
];
...这将为我提供以下新数组
var newarray= [
["1001","dog","mouse"],
["1002","cat"],
["1003","cat","mouse","cow"],
["1004","dog","cow"],
];
我已经完全迷惑了自己。感谢您的帮助。
答案 0 :(得分:1)
首先,您应该将arraylookup
转换为对象,即:
const objLookUp= {
"P6": "dog"],
"P7": "cat",
...
};
const arrayLookUp= [
["P6","dog"],
["P7","cat"],
["P8","mouse"],
["P9","horse"],
["P10","cow"],
];
const objLookUp = arrayLookUp.reduce((r, [key, value]) => (r[key]= value, r), {});
console.log(objLookUp);
然后,将输入数组转换为所需格式会更加容易:
const mainArray = [
["1001","P6","P8"],
["1002","P7"],
["1003","P7","P8","P10"],
["1004","P6","P10"],
];
const arrayLookUp= [
["P6","dog"],
["P7","cat"],
["P8","mouse"],
["P9","horse"],
["P10","cow"],
];
const objLookUp = arrayLookUp.reduce((r, [key, value]) => (r[key]= value, r), {});
const result = mainArray.map(
arr => arr.map(v => v in objLookUp ? objLookUp[v] : v)
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }