Home > Web Front-end > JS Tutorial > How to Create an Object from Arrays of Keys and Values in JavaScript?

How to Create an Object from Arrays of Keys and Values in JavaScript?

DDD
Release: 2024-10-24 22:28:30
Original
947 people have browsed it

How to Create an Object from Arrays of Keys and Values in JavaScript?

How to Construct an Object from Arrays of Keys and Values

Creating an object by pairing elements from two arrays can be a common programming task. Given an array of keys (e.g., ["Name", "Age", "Email"]) and an array of corresponding values (e.g., ["Jon", 15, "[email protected]"]), the goal is to construct an object that associates each key with its matching value (e.g., { Name: "Jon", Age: 15, Email: "[email protected]" }).

Solution:

To create an object from arrays of keys and values, a straightforward approach using JavaScript's forEach() method can be employed:

<code class="js">const keys = ['foo', 'bar', 'baz'];
const values = [11, 22, 33];

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

console.log(result); // { foo: 11, bar: 22, baz: 33 }</code>
Copy after login

Explanation:

  • Initialize an empty object (result) to store the key-value pairs.
  • Use the forEach() method to iterate through the keys array.
  • For each key, set the corresponding value from the values array at the same index (i.e., result[key] = values[i]).
  • The result object is gradually populated with the key-value pairs.

This simple technique effectively associates elements from the two arrays and creates the desired object by dynamically constructing its properties.

The above is the detailed content of How to Create an Object from Arrays of Keys and Values in JavaScript?. 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