Convert a JSON object array containing "Apple and Orange" to two separate strings, "Apple" and "Orange," using JavaScript

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!

Answer №1

To avoid directly modifying the existing food objects, it is recommended to create a new array. This new array should have the Fruit values separated into arrays by splitting them on " and ", while keeping the rest of the properties intact.

const response = {
  responseText: `[{"Veg":"Potato","Fruit":"Apple and Orange"},{"Veg":"Pumpkin","Fruit":"Orange and Orange"},{"Veg":"Potato","Fruit":"Banana"},{"Veg":"Onion","Fruit":"Mango and Orange"}]`
}

const food = JSON.parse(response.responseText)

const mapped = food.map(({ Fruit, ...rest }) => ({
  ...rest,
  Fruit: Fruit.split(" and "),
}))

console.log(mapped)
.as-console-wrapper { max-height: 100% !important; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After submitting the form, my goal was to show an alert using a combination of PHP, JavaScript, HTML, and AJAX

When the form is submitted to the bank, I would like it to display an alert message saying "Your message was sent" if successful, and "Error sending your message" if there was an issue. Currently, the code I'm using is not displaying alerts but showin ...

Send key-value pairs to the function using ng-model

I am currently working on a functionality that involves extracting an object from json and displaying its key-value pairs using 'ng-repeat' in AngularJS. The form includes checkboxes where the value can be either true or false, determining if the ...

What is the best way to automatically adjust a panel's width and height based on the user's screen resolution?

My page is connected to a masterpage. Within this page, I have an update panel that contains an ASP.NET panel. The panel includes a gridview displaying data from the database. Currently, I have set a fixed width and height for the panel. However, if the u ...

What is the best way to incorporate multiple variables in a MySQL query when using Node.js?

I'm facing a challenge where I need to input student data into a table using the parent key as a foreign key. The parent information is included in the same JSON object, with an array of students inside it. My goal is to retrieve the parent Id from th ...

Trouble with scrolling on Kendo chart while using mobile device

I am facing an issue with multiple kendo charts on my website. These charts have panning and zooming enabled, but in the mobile view, they take up 100% of the width which causes touch events to not work properly for scrolling. I attempted to attach an even ...

Having trouble showing image on an Android app using JSON parser from a webpage

Recently, I started working on Android development and am currently dealing with parsing web page data using JSON. I followed the androidhive JSON parser tutorial and was able to successfully parse the title but faced difficulties with parsing the image. D ...

Update the URL path with the selected tab item displayed

Is there a way to show the selected tab item in the URL path? I came across this example using Material UI: import * as React from 'react'; import Tabs from '@mui/material/Tabs'; import Tab from '@mui/material/Tab'; import Typ ...

change the property of an object in JavaScript

Trying to make changes to an item in an object (result of finding in a collection). Collection name: {}, date: {} Examples of documents in the collection [ {name: "pedro", date: "2018/01/01"}, {name: "juan", date: "2018/02/02"} ] Working with ...

Enhance Data Filtering in Ag-Grid Using Vue.js

Seeking assistance with Ag Grid in Vue js. I have a scenario where I want to disable the checkbox in the filter upon initial load so that the grid does not display records initially. Is this achievable? For example, in the screenshot provided in the link ...

Iterating over a JSON object with an embedded index in Angular using ng-repeat

Here is the structure of a JSON object: { "0": { "Order_Id": "100000001", "prodct_Status": "Pending", "Price": "8.0000", "date_created": "Jun 4, 2014 7:55:42 AM", "Shipping_Address": "vbccv", "Region": ...

Problem with redirecting when using HTTPS

I recently implemented an SSL Certificate and made changes to the web.config file. Here is the updated code: <system.webServer> <rewrite> <rules> <rule name="removed by me" stopProcessing="true"> ...

Unirest is having difficulty identifying the Gson mapper

Can you help me understand why unirest is unable to recognize the gson mapper dependency in my pom.xml file? This issue is preventing me from using the asJson() method, which is throwing an exception: Caused by: kong.unirest.UnirestConfigException: No Js ...

Converting a JSON object to an array with the help of JavaScript

Looking for help with converting and pushing data from a jQuery ajax request in json format into an array. Thanks in advance. [{"Day":"Nov 03","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null}, {"Day":"Nov 06","Saavor Kitchen":null,"Home Kitchen": ...

The system does not acknowledge 'CI' as a command that can be used internally or externally, functioning program, or batch file

Every time I attempt to execute npm run build in my React project, a persistent error keeps popping up: 'CI' is not recognized as an internal or external command, operable program or batch file. I have exhausted all troubleshooting steps - fro ...

A TypeError was encountered: Attempting to read the 'substr' property of an undefined variable

Recently, I encountered an issue while working on a script with jquery.min.js version 1.4. The problem arose when I had to upgrade the script to version 1.9.1. Uncaught TypeError: Can not read property 'substr' of undefined. I need assistance i ...

What significance does the slash hold in a package name when using require for an npm package?

When we "require" non-local NodeJS modules, what does the slash in the module name signify? For instance: from the GitHub page of the ShellJS npm module (link: https://github.com/shelljs/shelljs#javascript) require('shelljs/global'); requir ...

The AJAX POST response shows [object Object]{}

Here is the snippet of Javascript code I am working with: var paymentForm = $('#payment_form, .payment-invoices-container'); var ocodes = paymentForm.find('[name="ocodes"]:enabled'); alert(ocodes); $.post( 'https://URL/ajax- ...

Error: Unexpected termination of data in JSON file on line 2, starting at the first character

I keep encountering an error while trying to execute a basic JSON request. Check out the following PHP code that contains the data: <?php header('Content-Type: application/json; charset=utf-8'); $wealth = array( "name" => &q ...

Swapping out a sequence of characters in a web address with a different set

Swapping out imgur for filmot, Enter URL - https://i.stack.imgur.com/Uguvn.jpg Click the submit button After clicking submit, a new tab should open with the link .filmot.com/abcde.jpg. <html> <head> <title>input</title> <sc ...

What is the best way to update only the fields in a user's profile that they have filled out in the form?

I am having an issue updating user profile details using my form, as it only works when all input fields are filled. How can I update only the profile details that are filled in the form? The form allows for updating 4 fields: Name, Email, Age, and Passwo ...