Ask Your Question
2

How can a Javascript object be created using two arrays?

asked 2022-04-30 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-08-16 23:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-30 11:00:00 +0000

Seen: 14 times

Last updated: Aug 16 '22