Home  >  Article  >  Web Front-end  >  How can I create a JavaScript object from arrays of keys and values?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 09:15:28603browse

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' }

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!

Statement:
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