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'},
]
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);
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]} );
};