如何從兩個不同長度的陣列創建物件陣列
例如
arr1 = ["first","second","third","fourth","fifth","Sixth"]
arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]]
finalArray = [{
first:1,
second:2
third:3,
fourth:4,
fifth:5,
sixth:6
},{
first:7,
second:8
third:9,
fourth:10,
fifth:11,
sixth:12
}]
我嘗試使用 map 但將每個鍵值對作為整個物件
例子
[
{first: 1}
{second: 2}
{third: 3}
{fourth: 4}
]
uj5u.com熱心網友回復:
隨著map()和reduce():
const arr1 = ["first", "second", "third", "fourth", "fifth", "Sixth"];
const arr2 = [["1", "2", "3", "4", "5", "6"],
["7", "8", "9", "10", "11", "12"],
["1", "2", "3", "4"]];
const res = arr2.map(v => v.reduce((a, v, i) => ({...a, [arr1[i]]: v}), {}));
console.log(res);
uj5u.com熱心網友回復:
你可以利用Array.prototype.reduce來更新結果陣列的形狀
let arr1 = ["first","second","third","fourth","fifth","Sixth"];
let arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]];
let result = arr2.reduce((accumulator, current) => {
let obj = arr1.reduce((acc, currentKey, index) => {
if(current.indexOf(index) && current[index] !== undefined ){
acc[[currentKey]] = current[index];
}
return acc;
}, {});
return accumulator.concat(obj);
}, []);
console.log(result);
uj5u.com熱心網友回復:
reduce()當arr1包含較少元素作為元素時,沒有和覆寫的邊緣情況arr2
const arr1 = ["first","second","third","fourth","fifth","Sixth"]
const arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]]
const res = arr2.map(values => {
const res = {}
for(const [index, value] of arr1.entries()){
if(values[index]) {
res[value] = values[index] // or parseInt(values[index])
} else {
break
}
}
return res
})
console.dir(res)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339669.html
標籤:javascript 数组
下一篇:為什么我不能在JS中匯入模塊
