EN
JavaScript - how to convert array of key-value tuples into object?
1
answers
0
points
How can I convert an array of key-value tuples into an object in JavaScript?
Let's say I have the following array:
const array = [
['id', '1'],
['name', 'Tom'],
['age', '21'],
['premium', 'true'],
];
The result I want to get is:
{ id: '1', name: 'Tom', age: '21', premium: 'true' }
1 answer
0
points
The Object.fromEntries() method does exactly what you need.
Note:
The
Object.fromEntries()has been introduced in ECMAScript 2019 (ES10).
Practical example using fromEntries() (ES10+)
// ONLINE-RUNNER:browser;
const array = [
['id', '1'],
['name', 'Tom'],
['age', '21'],
['premium', 'true'],
];
const object = Object.fromEntries(array);
console.log(JSON.stringify(object)); // { id: '1', name: 'Tom', age: '21', premium: 'true' }
Alternative solution using forEach()
This solution also works with older versions of JavaScript.
// ONLINE-RUNNER:browser;
var array = [
['id', '1'],
['name', 'Tom'],
['age', '21'],
['premium', 'true'],
];
var object = {};
array.forEach(function(data) {
object[data[0]] = data[1];
});
console.log(JSON.stringify(object)); // { id: '1', name: 'Tom', age: '21', premium: 'true' }
See also
References
0 comments
Add comment