One way to create a JavaScript object using two arrays is by iterating over one array and using each element as a key while assigning the corresponding element from the other array as the value. Here is an example:
const keys = ['name', 'age', 'gender'];
const values = ['John', 30, 'male'];
const obj = {};
keys.forEach((key, index) => {
obj[key] = values[index];
});
console.log(obj); // { name: 'John', age: 30, gender: 'male' }
This code creates two arrays, keys
and values
, with the same number of elements. It then creates an empty object obj
. Using the forEach
method, it iterates over the keys
array and assigns each element as a key in the obj
object, while using the corresponding element from the values
array as the value. Finally, it logs the resulting object to the console.
Asked: 2022-04-30 11:00:00 +0000
Seen: 14 times
Last updated: Aug 16 '22