-2

I have Array of Array in JavaScript as follows:

myarr = [Array(3), Array(3)]

It has values:

[
 ['ID', 'Name', 'BloodGroup'],
 [1, 'Jim', 'B+'],
 [2, 'Jane', 'A+']
]

I want array of object as:

[{'ID':1,'Name':'Jim', 'BloodGroup': 'B+'}, ....]

Is there any way to achieve this using plain js or jQuery without using for loop, as data I get might be big, and server side is not an option.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
elpidaguy
  • 624
  • 1
  • 11
  • 25

1 Answers1

2

Destructing is perhaps a way to go?

const arr = [
  ['ID', 'Name', 'BloodGroup'],
  [1, 'Jim', 'B+'],
  [2, 'Jane', 'A+']
]
const titles = data[0]; // not used yet
const obj = arr.slice(1).map(([ID, Name, BloodGroup]) => ({ ID, Name, BloodGroup }))
console.log(obj)

I think I might miss one more level of abstraction using the titles but I am still investigating

@NinaScholz got me a more abstract example

const arr = [
  ['ID', 'Name', 'BloodGroup'],
  [1, 'Jim', 'B+'],
  [2, 'Jane', 'A+']
]
const titles = arr[0]; 

const obj = arr.slice(1).map(
  arr => Object.fromEntries(
    titles.map( 
      (t, i) => [t, arr[i]] 
    )
  )
);

console.log(obj)
mplungjan
  • 169,008
  • 28
  • 173
  • 236