skip to Main Content

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


  1. Since the indexes are same you can iterate over same and do the operations as:

    var cols_names = ['name', 'address', 'phoneno'];
    var arr_of_arrs = [
        ['ABC', 'INDIA', '0989898976'],
        ['XYZ', 'USA', '0989898998'],
        ['CDE', 'UK', '0989898956']
    ];
    
    var result = arr_of_arrs.map(function(arr) {
        var obj = {};
        cols_names.forEach(function(col, index) {
            obj[col] = arr[index];
        });
        return obj;
    });
    
    console.log(result);
    Login or Signup to reply.
  2. Try the following:

    var cols_names=['name','address','phoneno'];
    var arr_of_arrs=[
        ['ABC','INDIA','0989898976'],
        ['XYZ','USA','0989898998'],
        ['CDE','UK','0989898956']
        ];
        
    const res=arr_of_arrs.map(r=>Object.fromEntries(r.map((v,i)=>[cols_names[i],v])));
    
    console.log(res)

    This is very similar to what @NeERAJTK did, only using .map() instead of a .forEach() loop.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search