Languages

JavaScript - how to convert array of key-value tuples into object?

0 points
Asked by:
Maison-Humphries
821

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
Answered by:
Maison-Humphries
821

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

  1. JavaScript - ECMAScript / ES versions and features

References

  1. Object.fromEntries() - JavaScript | MDN
  2. Array.prototype.forEach() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join