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

How can I create a JavaScript object from arrays of keys and values?

Barbara Streisand
Release: 2024-10-25 09:15:28
Original
602 people have browsed it

How can I create a JavaScript object from arrays of keys and values?

Creating Objects from Arrays of Keys and Values

In many programming scenarios, you may encounter the need to create an object based on a set of keys and values. Suppose you have two arrays, newParamArr and paramVal, where newParamArr contains key names, and paramVal holds corresponding values. Your goal is to construct a single JavaScript object that maps these keys to values.

To achieve this, you can leverage the forEach method to iterate through the newParamArr array. For each element in the array, use bracket notation to assign the corresponding value from the paramVal array as the property value of the object being created.

const keys = ['Name', 'Age', 'Email'];
const values = ['Jon', 15, 'example@email.com'];

const result = {};
keys.forEach((key, index) => {
  result[key] = values[index];
});

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

By utilizing this approach, you can efficiently construct an object that mirrors the key-value structure defined by the input arrays, regardless of their length, as long as they maintain matching lengths.

The above is the detailed content of How can I create 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
Latest Articles by Author
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!