Home >Backend Development >PHP Tutorial >How to convert multidimensional array into object?
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 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!