I’ve been facing issues in making array of objects using array and array of arrays. In my scenario I’m having 400 cols and 5000 rows. Having col names in separate array and user data in array of arrays.
My Expectation:
Array of objects = Array (Cols_name) + Array_of_arrays (User_data)
var cols_names=['name','address','phoneno'];
var arr_of_arrs=[
['ABC','INDIA','0989898976'],
['XYZ','USA','0989898998'],
['CDE','UK','0989898956']
];
const arr_of_obj = arr_of_arrs.map((...cols_names) => ({cols_names}));
console.log(arr_of_obj);
I got output like this:
[
{ cols_names: [ [Array], 0, [Array] ] },
{ cols_names: [ [Array], 1, [Array] ] },
{ cols_names: [ [Array], 2, [Array] ] }
]
I need like this:
[
{
"name":"ABC",
"address":"INDIA",
"phoneno":"0989898976"
},
{
"name":"XYZ",
"address":"USA",
"phoneno":"0989898998"
},
{
"name":"CDE",
"address":"UK",
"phoneno":"0989898956"
}
]
Note: I can’t write the below code like this because I’m having 400 cols. I should not specify each and every col names statically in the code:
const arr_of_obj = arr_of_arrs.map(([name,address,phoneno]) => ({name, address,phoneno}));
console.log(arr_of_obj);
2
Answers
Since the indexes are same you can iterate over same and do the operations as:
Try the following:
This is very similar to what @NeERAJTK did, only using
.map()
instead of a.forEach()
loop.