How to convert two arrays of the same length into an object array in javascript
时间: 2024-05-01 07:17:07 浏览: 9
You can convert two arrays of the same length into an object array in JavaScript by using the `map()` function. Here's an example:
```javascript
const keys = ['name', 'age', 'city'];
const values = ['John Doe', 30, 'New York'];
const objArray = keys.map((key, index) => ({ [key]: values[index] }));
console.log(objArray); // [{ name: 'John Doe' }, { age: 30 }, { city: 'New York' }]
```
In this example, we have two arrays: `keys` and `values`. We want to create an object array where each object has a key-value pair from the two arrays. We use the `map()` function to iterate over the `keys` array and create a new object with the current key and the corresponding value from the `values` array. The resulting array is an array of objects with a single key-value pair each.