2

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

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

Comments

4

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.