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