Combining Key-Value Arrays into a JavaScript Object
Creating an object from two arrays, one containing keys and the other containing values, is a common task in JavaScript. This allows you to quickly construct objects without having to manually specify each key-value pair.
SOLUTION:
To combine the newParamArr and paramVal arrays into an object, you can use the forEach method and a concise arrow function:
<code class="javascript">const keys = ['Name', 'Age', 'Email']; const values = ['Jon', 15, 'example@email.com']; const result = {}; keys.forEach((key, i) => result[key] = values[i]); console.log(result); // { Name: 'Jon', Age: 15, Email: 'example@email.com' }</code>
This solution uses the forEach method with an arrow function to iterate over both arrays, creating a new key-value pair for each element. The i variable represents the index of the current element, allowing you to access the corresponding values from both arrays.
Optimizations:
If your arrays may contain thousands or millions of elements, you can use the following optimized version to minimize memory allocations and improve performance:
<code class="javascript">const keys = ['Name', 'Age', 'Email']; const values = ['Jon', 15, 'example@email.com']; let result = {}; for (let i = 0, len = keys.length; i < len; i++) { result[keys[i]] = values[i]; }</code>
By using a for loop instead of forEach, and pre-calculating the array length, this solution significantly reduces unnecessary memory allocations and improves iteration speed.
The above is the detailed content of How to Combine Key-Value Arrays into a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!