Home > Web Front-end > JS Tutorial > How do you create a JavaScript object from two arrays of keys and values?

How do you create a JavaScript object from two arrays of keys and values?

Barbara Streisand
Release: 2024-10-25 06:18:02
Original
696 people have browsed it

How do you create a JavaScript object from two arrays of keys and values?

Constructing an Object from Key and Value Arrays

You have two arrays, newParamArr and paramVal, and you aim to create a JavaScript object by pairing elements from these arrays. Each key in the object should correspond to an element in newParamArr, and the associated value should come from paramVal.

For example, if newParamArr contains ["Name", "Age", "Email"] and paramVal contains ["Jon", 15, "[email protected]"], you want to create an object like {"Name": "Jon", "Age": 15, "Email": "[email protected]"}.

The lengths of the arrays will always be equal (newParamArr.length === paramVal.length). Additionally, the arrays may vary in size.

To achieve this, you can utilize the forEach() method on the newParamArr array. The callback function you provide to forEach() takes the current key and its index as arguments. Within this function, you can assign the corresponding value from paramVal to the object using the key as the property name.

This approach is straightforward and efficient for creating an object from key-value arrays. Here's a code snippet that implements this solution:

<code class="js">var keys = ['Name', 'Age', 'Email'];
var values = ['Jon', 15, '[email protected]'];

var result = {};
keys.forEach((key, i) => result[key] = values[i]);
console.log(result);</code>
Copy after login

This code will log the desired object, { Name: "Jon", Age: 15, Email: "[email protected]" }.

The above is the detailed content of How do you create a JavaScript object from two 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