Ben Franklin
Ben Franklin

Reputation: 7

Array of Array into Array of object in javascript

i have a array of array lets call it x

let x = [
  ["Last Name", "First Name", "Email Address", "Role", "Employee id (optional)"],
  ["Smith", "John", "[email protected]", "Employee", "ABC123XYZ"],
  ["Doe", "Jane", "[email protected]", "Verifier", "ABC123XYZ"]
]

how do i make it to

[
  {
    "Last Name": "Smith",
    "First Name": "John",
    "Email Address": "[email protected]",
    "role": "Employee",
    "Employee id": "ABC123XYZ"
  },

  {
    "Last Name": "Doe",
    "First Name": "Jane",
    "Email Address": "[email protected]",
    "role": "Verifier",
    "Employee id": "ABC123XYZ"
  }
]

how to construct a function which can return the above format

Upvotes: 1

Views: 58

Answers (1)

hgb123
hgb123

Reputation: 14891

You could use map

let x = [
  ['Last Name', 'First Name', 'Email Address', 'Role', 'Employee id'],
  ['Smith', 'John', '[email protected]', 'Employee', 'ABC123XYZ'],
  ['Doe', 'Jane', '[email protected]', 'Verifier', 'ABC123XYZ']
]

const [props, ...data] = x

const res = data.map(d => {
  const obj = {}
  d.forEach((value, index) => {
    obj[props[index]] = value
  })
  return obj
})

console.log(res)

Upvotes: 2

Related Questions