-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.

8
  • Have you tried something? Commented Jun 4, 2020 at 14:11
  • Please visit the help center, take the tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output using the [<>] snippet editor. Commented Jun 4, 2020 at 14:12
  • jQuery is never needed to map an array Commented Jun 4, 2020 at 14:12
  • @Sfili_81 I had crude logic with for loops, but performance wise need different solution, I searched various similar questions here with map reduce, but those weren't too helpful in my case Commented Jun 4, 2020 at 14:13
  • Why not do this on the server that creates the arrays? It looks like CSV Commented Jun 4, 2020 at 14:14

1 Answer 1

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)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.