Currently, I have a JSON object retrieved from an external source:
[
{
"Veg": "Potato",
"Fruit": "Apple and Orange"
},
{
"Veg": "Pumpkin",
"Fruit": "Orange and Orange"
},
{
"Veg": "Potato",
"Fruit": "Banana"
},
{
"Veg": "Onion",
"Fruit": "Mango and Orange"
}
]
I need assistance in modifying the fruit section. Currently, it displays Fruit A 'and' Fruit B. My goal is to remove 'and' and list the fruits separately.
The desired output should look like this:
[
{
"Veg": "Potato",
"Fruit": [
"Orange",
"Apple"
]
},
{
"Veg": "Pumpkin",
"Fruit": [
"Orange",
"Orange"
]
},
{
"Fruit": [
"Banana"
]
},
{
"Veg": "Onion",
"Fruit": [
"Mango",
"Orange"
]
}
]
I attempted to split the fruit using JavaScript but faced difficulties as it created new instead of replacing them directly. Here is the code snippet:
var food = JSON.parse(request.responseText);
for(let i = 0; i < food.length; i++){
let foodSplit = food[i].Fruit.split(' and ');
if(foodSplit.length > 0){
food[i].Fruit1 = foodSplit[0];
food[i].Fruit2 = foodSplit[1];
}
}
Any assistance would be greatly appreciated!