Home > Web Front-end > JS Tutorial > body text

How to Combine Key-Value Arrays into a JavaScript Object?

Susan Sarandon
Release: 2024-10-25 02:44:29
Original
624 people have browsed it

How to Combine Key-Value Arrays into a JavaScript Object?

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>
Copy after login

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>
Copy after login

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!

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