Ваш ожидаемый результат не выглядит действительным JS. Однако вы можете получить массив массивов, выполнив итерацию по нему, используя несколько методов, таких как .reduce()
, .map()
и Object.entries()
:
const data = [
{ReportTime: "30 Apr 2017BDT", Rate: "1.00000", AvgGrowth: "0.0"},
{ReportTime: "30 Apr 2017BDT", Rate: "0.01107", AvgGrowth: "0.1"},
{ReportTime: "29 Apr 2017BDT", Rate: "1.00000", AvgGrowth: "0.0"},
{ReportTime: "29 Apr 2017BDT", Rate: "0.01107", AvgGrowth: "-0.5"}
];
const result = Object.entries(
data.reduce((r, {ReportTime, ...rest}) => {
r[ReportTime] = (r[ReportTime] || []).concat(Object.values(rest));
return r;
}, {})
).map(([k, v]) => [k, ...v]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Вот альтернативный подход, использующий синтаксис es5 (старый):
var data = [
{ReportTime: "30 Apr 2017BDT", Rate: "1.00000", AvgGrowth: "0.0"},
{ReportTime: "30 Apr 2017BDT", Rate: "0.01107", AvgGrowth: "0.1"},
{ReportTime: "29 Apr 2017BDT", Rate: "1.00000", AvgGrowth: "0.0"},
{ReportTime: "29 Apr 2017BDT", Rate: "0.01107", AvgGrowth: "-0.5"}
];
var key = 'ReportTime';
var reducer = function(data, key) {
var result = [];
var map = {};
data.forEach(function(o, i) {
map[o[key]] = map[o[key]] || [];
for(var k in o) {
if(!(k === key)) { map[o[key]].push(o[k]); }
};
});
for(var j in map) {
result.push([].concat(j, map[j]));
};
return result;
};
console.log(reducer(data, key));