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
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);
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.