I have a source multidimensional array. It looks like:
var arr = [];
arr[1] = [];
arr[2] = [];
arr[3] = [];
arr[1][1] = "11";
arr[1][2] = "12";
arr[1][3] = "13";
arr[2][1] = "21";
arr[2][2] = "22";
arr[2][3] = "23";
arr[3][1] = "31";
arr[3][2] = "32";
arr[3][3] = "33";
I need to convert this to a flat array using ES6 features. Result must looks like this:
var res = [
{ col:1, row:1, val:"11"},
{ col:1, row:2, val:"12"},
{ col:1, row:3, val:"13"},
{ col:2, row:1, val:"21"},
{ col:2, row:2, val:"22"},
{ col:2, row:3, val:"23"},
{ col:3, row:1, val:"31"},
{ col:3, row:2, val:"32"},
{ col:3, row:3, val:"33"}
];
You could use Array#reduce
and Array#forEach
for new objects.
var arr = [, [, '11', '12', '13'], [, '21', '22', '23'], [, '31', '32', '33']], result = arr.reduce((r, a, col) => (a.forEach((val, row) => r.push({ col, row, val })), r), []); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.