Javascript: How do you turn an array into an object?

Asked 2 years ago, Updated 2 years ago, 84 views

Hello.

Array below

const data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];

I want to change it to the object below.

const data = [
  {
    a: 1,
    b: 2,
    c: 3,
    d: 4
  },
  {
    a: 5,
    b: 6,
    c: 7,
    d: 8
  },
  {
    a: 9,
    b: 10,
    c: 11,
    d: 12
  }
];

How do I write a repeat sentence or something else?

Thank you.

javascript object array

2022-09-21 18:58

1 Answers

I'm sorry, I solved it.

const toObj = data.map(([ a, b, c, d ]) => ({ a, b, c, d }));

console.log(toObj);

The console is photographed as follows:

[
  {
    "a": 1,
    "b": 2,
    "c": 3,
    "d": 4
  },
  {
    "a": 5,
    "b": 6,
    "c": 7,
    "d": 8
  },
  {
    "a": 9,
    "b": 10,
    "c": 11,
    "d": 12
  }
]


2022-09-21 18:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.