0

Actual Output :

[["Name","Age","Location","Gender"],["Mary",28,"KY","F"],["Jonathan",34,"NJ","M"],["Kevin",31,"CA","M"]]

Expected output :

[
  {
    "Name":"Mary",
    "Age":28,
    "Location":"KY" ,
    "Gender":"F"
  },
  {
    "Name":"Jonathan",
    "Age":34,
    "Location":"NJ",
    "Gender":"M"
  },
  {
    "Name":"Kevin",
    "Age":31,
    "Location":"CA",
    "Gender":"M"
  }
] 

Please help me with this. So that I can iterate in table.

Thanks in advance

2 Answers 2

1

Try this:

const input = [["Name", "Age", "Location", "Gender"], ["Mary", 28, "KY", "F"], ["Jonathan", 34, "NJ", "M"], ["Kevin", 31, "CA", "M"]];
const keys = input[0];
const output = input.slice(1).map(entry => {
    const retVal = {};
    keys.forEach((key, index) => {
        retVal[key] = entry[index];
    });
    return retVal;
});
console.log(output);

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

Comments

1

Destructure the keys from the values. Map the array of values (vals), and use Object.fromEntries() to create an object by mapping each values sub-array (varr), and combining with the respective key to create an array of [key, value] entries.

to create an object from the values and the keys:

const objecttify = ([keys, ...vals]) => // destructure the keys and an array of values
  vals.map(varr => // map the values
    Object.fromEntries( // convert the entries to an object
      varr.map((v, i) => [keys[i], v]) // create the entries by combining a value with it's respective key
    )
  )

const arr = [["Name","Age","Location","Gender"],["Mary",28,"KY","F"],["Jonathan",34,"NJ","M"],["Kevin",31,"CA","M"]]

const result = objecttify(arr)

console.log(result)

1 Comment

Thank you so much for explanation.

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.