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>
Explanation:
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!