我在將數組類對象轉換爲對象數組時遇到了一些麻煩。我正在使用reduce方法,它正確地將數組數據轉換爲第一組數組的對象,但第二次通過時,它將數據正確地設置爲key:value對,但不會將其放置在I希望它是在將數組對象的多深度數組轉換爲對象數組
這裏是陣列和功能:
var array = [
[
['Name', 'Arusha'], ['Species', 'Arabica'], ['Region', 'Mount Meru in Tanzania, and Papua New Guinea'], ['Comments', 'Typica variety or a French Mission']
],
[
['Name', 'Catimor'], ['Species', 'Interspecific hybrid'], ['Region', 'Latin America'], ['Comments', 'This is cross between Timor coffee and Caturra coffee. It was created in Portugal in 1959']
]
];
function convertArrayToObject(array) {
var arr = [];
array.reduce(function(result, currentArray) {
for (var j = 0, i = 0; i < array[0].length; i++) {
result[currentArray[i][0]] = currentArray[i][1];
}
arr.push(result);
return arr;
}, {});
return arr;
}
我的預期輸出是假設是這個樣子:
[
{ Name: 'Arusha', Species: 'Arabica', Region: 'Mount Meru in Tanzania, and Papua New Guinea', Comments: 'Typica variety or a French Mission' },
{ Name: 'Catimor', Species: 'Interspecific hybrid', Region: 'Latin America', Comments: 'This is cross between Timor coffee and Caturra coffee. It was created in Portugal in 1959' }
]
這就是我目前返回:
[ { Name: 'Arusha', Species: 'Arabica', Region: 'Mount Meru in Tanzania, and Papua New Guinea', Comments: 'Typica variety or a French Mission' },
[Circular],
Name: 'Catimor',
Species: 'Interspecific hybrid',
Region: 'Latin America',
Comments: 'This is cross between Timor coffee and Caturra coffee. It was created in Portugal in 1959' ]
任何幫助將不勝感激!
您正在尋找'地圖()' - >'reduce()' –
可能是lodash _flatMap會幫你 –
啊!我以爲你只是說使用地圖,但使用地圖,然後減少一定會做到這一點!謝謝! –