'how convert array to each array in javascript [closed]

Actually, I'm not sure if my title is correct.

If I have a data below like that,

const data = [
 fruit: ['apple','banana', 'peer'],
 vegetable: ['tomato','onion', 'leek']
]

How can I convert below that?

const filteredData = [
 {fruit: 'apple', vegetable: 'tomato'},
 {fruit: 'banana', vegetable: 'onion'},
 {fruit: 'peer', vegetable: 'leek'},
]


Solution 1:[1]

data is an object in that case. You can get the expected result using Array#map:

const data = { fruit: ['apple','banana', 'peer'], vegetable: ['tomato','onion', 'leek'] };

const arr = data.fruit.map((fruit, i) => ({ fruit, vegetable: data.vegetable[i] }));

console.log(arr);

Solution 2:[2]

Assuming data is this:

const data = {
    fruit: ['apple','banana', 'peer'],
    vegetable: ['tomato','onion', 'leek']
}
const filteredData = [];
for (let i = 0; i < data.fruit.length; i++) {
    filteredData.push({ fruit: data.fruit[i], vegetable: data.vegetable[i]} );
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Majed Badawi
Solution 2 Muhammed Jaseem