在 JavaScript 中将 2d 表格数据条目转换为对象数组
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有一个像这样的数组数组 −
const arr = [ ["Ashley","2017-01-10",80], ["Ashley","2017-02-10",75], ["Ashley","2017-03-10",85], ["Clara","2017-01-10",90], ["Clara","2017-02-10",82] ];
我们需要编写一个 JavaScript 函数,将一个这样的数组作为第一个也是唯一的输入。
然后,该函数应根据输入数组构造一个新的对象数组。该数组应包含输入数组的每个唯一子数组的对象。(在此上下文中,唯一是指其第一个元素唯一的子数组)。
每个对象必须具有以下架构 −
const output = [ {"name":"Ashley", "2017-01-10":80, "2017-02-10":75, "2017-03-10":85}, {"name":"Clara", "2017-01-10":90, "2017-02-10":82} ];
示例
const arr = [ ["Ashley","2017-01-10",80], ["Ashley","2017-02-10",75], ["Ashley","2017-03-10",85], ["Clara","2017-01-10",90], ["Clara","2017-02-10",82] ]; const groupArray = (arr = []) => { let grouped = []; grouped = arr.reduce(function (hash) { return function (r, a) { if (!hash[a[0]]) { hash[a[0]] = { name: a[0] }; r.push(hash[a[0]]); } hash[a[0]][a[1]] = a[2]; return r; }; } (Object.create(null)), []); return grouped; } console.log(groupArray(arr));
输出
控制台中的输出将是 −
[ { name: 'Ashley', '2017-01-10': 80, '2017-02-10': 75, '2017-03-10': 85 }, { name: 'Clara', '2017-01-10': 90, '2017-02-10': 82 } ]