Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert key-value object array into 2d array in javascript

Tags:

javascript

let th = ['name', 'id', 'class']
    
let arr = [
    { 'name' : 'a', 'class':'7', 'id':'1' },
    { 'name' : 'b', 'class':'7', 'id':'2' },
    { 'name' : 'b', 'class':'7', 'id':'3' },
    { 'name' : 'd', 'class':'7', 'id':'4' }
]
    
/* final array what is look like */
    
let finalArr = [
    ['a', '1', '7'],
    ['b', '2', '7'],
    ['c', '3', '7'],
    ['d', '4', '7']
]

How can I create this array without using forEach and map? This is a sample data, but in reality there are more than 10k data at a time so forEach is not a good option.

like image 527
Suraj Avatar asked Oct 16 '25 10:10

Suraj


1 Answers

You have a typo in the third row, fixed here:

let th = ['name', 'id', 'class'];

let arr = [
    { 'name': 'a', 'class': '7', 'id': '1' },
    { 'name': 'b', 'class': '7', 'id': '2' },
    { 'name': 'c', 'class': '7', 'id': '3' },
    { 'name': 'd', 'class': '7', 'id': '4' }
];

const transformedArr = arr.map(row => th.map(name => row[name]));
console.log(transformedArr);

If you want a faster solution, use for and pre-allocated arrays:

` Chrome/124
--------------------------------------------------------------------------------
>           n=4       |       n=40        |       n=400       |      n=4000     
for   ■ 1.00x x1m  99 | ■ 1.00x   x1m 956 | ■ 1.00x x100k 923 | ■ 1.00x x10k 931
map     1.25x x1m 124 |   1.16x x100k 111 |   1.25x  x10k 115 |   1.34x  x1k 125
--------------------------------------------------------------------------------
https://github.com/silentmantra/benchmark `
` Firefox/125
------------------------------------------------------------------------------
>           n=4       |       n=40        |      n=400       |     n=4000     
for   ■ 1.00x x1m 110 | ■ 1.00x x100k  95 | ■ 1.00x x10k  98 | ■ 1.00x x1k 104
map     1.56x x1m 172 |   1.62x x100k 154 |   1.85x x10k 181 |   1.60x x1k 166
------------------------------------------------------------------------------
https://github.com/silentmantra/benchmark `

let th = ['name', 'id', 'class'];

let $chunk = [
    { 'name': 'a', 'class': '7', 'id': '1' },
    { 'name': 'b', 'class': '7', 'id': '2' },
    { 'name': 'c', 'class': '7', 'id': '3' },
    { 'name': 'd', 'class': '7', 'id': '4' }
];

const $input = [], arr = $input;

// @benchmark map
arr.map(row => th.map(name => row[name]));

// @benchmark for
const result = Array(arr.length);

for (let i = 0; i < arr.length; i++) {
    const item = result[i] = Array(th.length);
    for (let j = 0; j < th.length; j++) {
        item[j] = arr[i][th[j]];
    }
}
result;

/*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));
like image 57
Alexander Nenashev Avatar answered Oct 18 '25 11:10

Alexander Nenashev