我对 JavaScript 完全陌生,正在学校学习初级类(class)。
我有一个作业,要求我们创建一个函数,通过使用列标题作为键,使用数据作为每行的值,将二维数组转换为字典。
我想我知道如何分隔第一行(用作标题)和其余行(用作行),但我在将其转换为字典时遇到问题。
这是我到目前为止所写的内容:
function rowsToObjects(data) {
var headers = data[1];
data.shift();
//var rows = alert(data);
var rows = alert(data.slice(1));
}
下面是输出的示例:
const headers = ['a', 'b', 'c'];//Should not be hardcoded - subject to change depending on the grader
const rows = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];//Should not be hardcoded - subject to change depending on the grader
const result = rowsToObjects({headers, rows})
console.log(result);
// [{a: 1, b: 2, c: 3}, {a: 4, b: 5, c: 6}, {a: 7, b: 8, c: 9}];
如果我可以使用 for 循环,我就会知道如何为每一行创建一个字典,但我们不允许使用 while 循环、for 循环、for ... in 循环、for ... of 循环, forEach 方法,所以我正在努力想出一种方法来做到这一点,并使我的输出看起来像示例中所示的那样。
欢迎任何帮助,非常感谢!
最佳答案
您可以在 rows
数组上使用 Array.prototype.reduce
来迭代 rows
二维数组中的每个数组。
然后,对于二维数组中的每个数组,使用 Array.prototype.reduce 创建一个临时对象,以映射与每个数组值对应的 headers
中的值使用索引 i
的 rows
数组:
const headers = ['a', 'b', 'c'];
const rows = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const result = rowsToObjects(headers, rows)
console.log(result);
// [{a: 1, b: 2, c: 3}, {a: 4, b: 5, c: 6}, {a: 7, b: 8, c: 9}];
function rowsToObjects(headers, rows){
return rows.reduce((acc, e, idx) => {
acc.push(headers.reduce((r, h, i)=> {r[h] = e[i]; return r; }, {}))
return acc;
}, []);
}
关于JavaScript:从二维数组(标题,行)创建键值数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58050534/