Convert a 2D array with first rows a headers to object JavaScript

Viewed 554

I have an array that has first rows as header:

array = [[ 'combi', 'DQ#', 'sd', 'Level 3', 'Level 6', 'Level 7' ], [ 'DQn DQDC Simple','DQn',  'DQDC', 'Simple', 'Simple_A7',  0.262],[ 'DQn DQDC Simple1','DQn',  'DQDC', 'Simple1', 'Simple_A7',  0.264]]

convert this into a json object format:

new_obj = [{"combi":"DQ8 DQDC Simple","DQ#":"DQ8","Level 3":"DQDC","Level 6":"Simple","Level 7":"Simple_A7","sc_7":0.262}, {"combi":"DQ8 DQDC Simple1","DQ#":"DQ8","Level 3":"DQDC","Level 6":"Simple1","Level 7":"Simple_A7","sc_7":0.264}]

I've tried searching a lot on StackOverflow but didn't find the answer. Any suggestions would be highly appreciated

2 Answers

Destructure the array, and take the keys (1st item), and the values (the rest). Map the values array, and then map each sub-array of values, take the respective key by the value, and return a pair of [key, value]. Convert the array pairs to an object with Object.fromEntries():

const fn = ([keys, ...values]) => 
  values.map(vs => Object.fromEntries(vs.map((v, i) => [keys[i], v])))

const array = [[ 'combi', 'DQ#', 'sd', 'Level 3', 'Level 6', 'Level 7' ], [ 'DQn DQDC Simple','DQn',  'DQDC', 'Simple', 'Simple_A7',  0.262],[ 'DQn DQDC Simple1','DQn',  'DQDC', 'Simple1', 'Simple_A7',  0.264]]

const result = fn(array)

console.log(result)

Another option is to create the objects with Array.reduce() instead of Array.map() with Object.entries():

const fn = ([keys, ...values]) => 
  values.map(vs => vs.reduce((acc, v, i) => (acc[keys[i]] = v, acc), {}))

const array = [[ 'combi', 'DQ#', 'sd', 'Level 3', 'Level 6', 'Level 7' ], [ 'DQn DQDC Simple','DQn',  'DQDC', 'Simple', 'Simple_A7',  0.262],[ 'DQn DQDC Simple1','DQn',  'DQDC', 'Simple1', 'Simple_A7',  0.264]]

const result = fn(array)

console.log(result)

We can also achieve this using Spreading the initial array and separating keys and the values list as shown below.

let array = [['combi', 'DQ#', 'sd', 'Level 3', 'Level 6', 'Level 7'], ['DQn DQDC Simple', 'DQn', 'DQDC', 'Simple', 'Simple_A7', 0.262], ['DQn DQDC Simple1', 'DQn', 'DQDC', 'Simple1', 'Simple_A7', 0.264]];

//Separate Keys and Values into different variables
const [keysList, ...valuesList] = array;

//Loop through the values list
const result = valuesList.map(values => {
  let obj = {};
  //Since each element in values list is a list again
  //loop through the list and add them to the `obj` object
  values.forEach((val, i) => {
    obj[keysList[i]] = val
  });
  //return the object
  return obj;
});

console.log(result);

Related