How to convert multidimensional array into object?

王林
Release: 2024-04-30 08:15:01
Original
897 people have browsed it

In JavaScript, converting a multidimensional array to an object requires the following steps: Use the reduce() method to generate an array of key-value pairs. Convert an array of key-value pairs to an object using the Object.assign() method.

How to convert multidimensional array into object?

How to convert multi-dimensional arrays to objects

In JavaScript, converting multi-dimensional arrays to objects is a common need. This can be achieved by following the steps:

1. Use the reduce() method to generate an array of key-value pairs:

const arr = [
  ['name', 'John Doe'],
  ['age', 25],
  ['city', 'New York']
];

const keyValueArr = arr.reduce((acc, cur) => {
  const [key, value] = cur;
  acc[key] = value;
  return acc;
}, {});
Copy after login

2. Use the Object.assign() method to convert an array of key-value pairs into an object:

const obj = Object.assign({}, ...keyValueArr);
Copy after login

Practical case:

Assume we have A multidimensional array containing user details as shown below:

const userData = [
  ['name', 'Jane Doe'],
  ['email', 'jane.doe@example.com'],
  ['address', '123 Main Street'],
  ['city', 'London'],
  ['country', 'United Kingdom']
];
Copy after login

We can convert it to an object using the above method:

const userObj = Object.assign({}, ...userData.reduce((acc, cur) => {
  const [key, value] = cur;
  acc[key] = value;
  return acc;
}, {}));
Copy after login

Result:

{
  name: 'Jane Doe',
  email: 'jane.doe@example.com',
  address: '123 Main Street',
  city: 'London',
  country: 'United Kingdom'
}
Copy after login

The above is the detailed content of How to convert multidimensional array into object?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template