Home > Web Front-end > JS Tutorial > body text

How Can I Build a JavaScript Object from Arrays of Keys and Values?

DDD
Release: 2024-10-25 01:09:02
Original
505 people have browsed it

How Can I Build a JavaScript Object from Arrays of Keys and Values?

Creating Objects from Arrays of Keys and Values

In the realm of JavaScript, it is often necessary to construct objects from arrays of keys and values. This task can be tackled with the aid of a simple algorithm that iterates through both arrays and maps the elements accordingly.

To illustrate this process, let's consider an example where we have two arrays: newParamArr and paramVal. The values in newParamArr represent the keys of the object we aim to create, while the values in paramVal represent the corresponding values for those keys.

For instance, if newParamArr contains the values ["Name", "Age", "Email"] and paramVal contains the values ["Jon", 15, "example@email.com"], we seek to create an object with the properties {Name: "Jon", Age: 15, Email: "example@email.com"}.

The following code snippet demonstrates how this can be achieved:

<code class="javascript">var keys = ['Name', 'Age', 'Email'];
var values = ['Jon', 15, 'example@email.com'];

var result = Object.fromEntries(keys.map((key, i) => ([key, values[i]])));

console.log(result); // { Name: 'Jon', Age: 15, Email: 'example@email.com' }</code>
Copy after login

In the code above, we utilize the Object.fromEntries method to construct the object. This method takes an iterable of key-value pairs and returns an object with the specified keys and values.

The key-value pairs are generated by mapping over the keys array and pairing each key with the corresponding value from the values array using the arrow function (key, i) => ([key, values[i]]).

This simple approach ensures that the resulting object will always have the appropriate properties and values, regardless of the length or contents of the input arrays.

The above is the detailed content of How Can I Build a JavaScript Object from Arrays of Keys and Values?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!