Home  >  Article  >  Backend Development  >  How to convert multidimensional array into object?

How to convert multidimensional array into object?

王林
王林Original
2024-04-30 08:15:01892browse

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;
}, {});

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

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

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']
];

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;
}, {}));

Result:

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

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!

Statement:
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
Previous article:Array slice reverse arrayNext article:Array slice reverse array