Efficiently sanitizing a JavaScript object using the replace() method in JavaScript

I have a data object structured like this

{"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{"lat":18.7675049,"lng":-103.1445221},"deliveryOptionmodal":{"id":3,"value":"Sin contacto/Dejar orden en la puerta","$$hashKey":"object:272"},"delivery_cost_new":10,"products":{"name":"Product"},"customer_id":35,"customer":"{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adc5c2c3cac6c2c3caddc4c9c8edcac0ccc4c183cec2c0">[email protected]</a>\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\"...

It may be hard to read in its current form. Is there a way to simplify and display it like this?

business_name: Sport Devy
name: hong kong

I would like to clean up the object to make it more presentable.

Answer №1

If you need the data in a different format, you can create a function to transform it accordingly. Whether you require it as a string or an object is not clear. The current function outputs a string, but it can be adjusted to return an object if necessary.

function convertData(obj) {
   const bname = obj.business_name;
   const customer = JSON.parse(obj.customer || "{}");
   const name = customer && customer.name;
   /* If you want an object:
   return {
     business_name: bname,
     name: name
   };
   */
   return [
    "business name: "+ bname,
    "name: " + name,
   ].join("\n");
};

const data = {"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{"lat":18.7675049,"lng":-103.1445221},"deliveryOptionmodal":{"id":3,"value":"Sin contacto/Dejar orden en la puerta","$$hashKey":"object:272"},"delivery_cost_new":10,"products":{"name":"Product"},"customer_id":35,"customer":"{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"<a href="/cdn-cgi/l/email-protection\" class="__cf_email__\" data-cfemail=\"741c1b1a131f1b1a13041d1011341319151d185a171b19\">[email protected]</a>\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}","business_name":"Soporte Devy"};

console.log(convertData(data));

Answer №2

const orderDetails = {
  "paymethod_id": 1,
  "business_id": 76,
  "delivery_type": "1",
  "driver_tip": 0,
  "delivery_zone_id": 6569,
  "delivery_datetime": null,
  "location": {
    "lat": 18.7675049,
    "lng": -103.1445221
  },
  "deliveryOptionmodal": {
    "id": 3,
    "value": "Sin contacto/Dejar orden en la puerta",
    "$$hashKey": "object:272"
  },
  "delivery_cost_new": 10,
  "products": {
    "name": "Product"
  },
  "customer_id": 35,
  "customer": "{\"id\":35,\"name\":\"Hong Kong\",\"middle_name\":null,\"lastname\":\"\",\"second_lastname\":null,\"photo\":\"https://res.cloudinary.com/ordering2/image/upload/v1551225299/taomauvuhrrowqqp3ncp.png\",\"email\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b7374757c7074757c6b727f">[email protected]</a>\",\"cellphone\":\"4433413248\",\"address\":\"Coalcomán, Mich., México\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":null,\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}",
  "business_name": "Soporte Devy"
}

business_name is accessible directly from the orderDetails object using orderDetails.business_name. The `customer` node needs to be converted into a JavaScript object; this can be achieved by using

JSON.parse(orderDetails.customer)

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

Removing elements from an array of objects using specific values stored in another array - JavaScript

I'm currently working on implementing a reducer in redux that can delete multiple items from the state based on an array of values. Let's say I have the following array: const idArray = ["935", "933", "930"]; My goal is to remove objects that ...

Troubleshooting a problem with jQuery child items

Could someone help me understand why the second div is affected by the last part of the code and not the first? It's puzzling to see all the content disappear, especially when I expected the first div to be impacted as it seems like the immediate pare ...

Generate a JSON object based on the request.body information

Currently using NodeJs along with Express for building a REST API. The functionality is all set up and running smoothly, but I'm facing an issue in comprehending how to iterate through the request.body object and validate its fields for any undefined ...

My AngularJS module seems to be malfunctioning

After spending a significant amount of time on this, I am really hoping for some assistance. I am currently working on creating a module that will generate a directive and controller for the header section of my AngularJS site. Despite not encountering any ...

Automatically integrating Nivo Lightbox into your website

I incorporated Nivo Lightbox into my website, seamlessly integrating all images with the plugin using the following code: <div class="portfolio-item"> <div class="portfolio-thumb "> <a class="lightbox" data-lightbox-type="ajax" title="Strat ...

Sequelize querying using the `WHERE NOT EXISTS()` condition

I am currently working with a many-to-many relationship setup in my database: var Genres = db.define('Movie', { name: { type: Sequelize.STRING(100), allowNull: false }, description: { type:Sequelize.STRING(), ...

Implementing a pull-to-refresh feature in React Native using Redux

I need to implement pull to refresh functionality, but I'm unsure of what to call from _Refresh(). My actions, constants, and reducers are stored on another page. How can I trigger the API again? Thank you in advance for your assistance. class Homewo ...

Fill in input field based on choice from the drop-down menu - JavaScript

I am facing an issue where I cannot add text inside the text box based on the dropdown selection. For example, if I select option2 from the dropdown, the textbox should be populated with option2. (function() { 'use strict'; setInterva ...

Are the props.children handled differently within the <Route> component compared to other React components?

Each and every react component undergoes a process in the following function, which is located in ReactElement.js within node_modules: ReactElement.createElement = function (type, config, children){ . . . } This function also encompasses <Rou ...

Encountered an ERESOLVE error when attempting to install a package, unable to resolve the dependency tree

After attempting to install the necessary dependencies for my project with npm install, an error message came up that I am unable to decipher: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: &l ...

Building a JSON array within an array within an input in Rails 4

Currently, the content within my form is as follows: <%= f.input :document, collection: @documents, wrapper: false, label: false, input_html: {class: 'fleft mleft5'} %> This will result in a JSON array: [{ "document":"126" }] In My C ...

React - Why does React fail to update the state when expected? (not retaining)

Hello there, I'm currently working on fetching JSON data from an API and populating it into a table. It seems pretty straightforward but here's where things get tricky – I can see that the "tableData" state is getting updated as new rows are ad ...

Retrieve the AJAX response, concatenate the data, and construct a dynamic table

I am facing an issue with assigning my AJAX return as a variable to concatenate. Here is the sample code: function FetchSex() { $.ajax({ url: '/SEX/GetAllSex/', success: function (responseDat ...

In the Firebug console, Ajax posts are highlighted in a vibrant red color

Upon executing the code provided, the Firebug was enabled. While submitting the form, in the console, the message "post to login_submit.php" appeared in red. However, there was no response received as well. <!DOCTYPE html> <html> ...

Sending form data using javascript without refreshing the page

I have a wall/social system similar to Facebook where users can post statuses. I want to add the functionality for users to like, dislike, and comment on a status without the page reloading. How can I achieve this with the form below? if(empty($_GET[&apos ...

The submission of the form is not functioning correctly when triggered by JavaScript using a button

My website was designed using a CSS/HTML framework that has been seamlessly integrated into an ASP.NET site. Within a ContentPlaceHolder, I have implemented a basic login form. The unique aspect is that I am utilizing the onclick event of an image to subm ...

What is the mechanism behind angular2's spa routing functioning seamlessly without the need for the hash character in the url?

During my experience with the Angular2 "Tour of Heroes" tutorial, I made an interesting observation about how their single page application router functions without a trailing hash symbol (#) in the URL. This differs from the Kendo SPA router, which typica ...

What is the best way to disregard all pathNames and display my index.php file directly from the root of my website?

After a user clicks on a navigation link on my website, the page is loaded into a content window within the same page using JavaScript. I then utilize HTML 5 to modify the URL and create a history entry, resulting in a URL resembling the one mentioned (). ...

What is causing the ajax code to malfunction?

I am new to ASP MVC and trying to create a login form using AJAX. I have written a JsonResult in the controller to check the username and password, but for some reason it is not working. Here is my controller code: public ActionResult login() { ...

Tips for resolving conflicts with jQuery on an ASP.NET webpage

On this page, I am using references and scripts for a date time picker and color box. However, only one of them works at a time - commenting out one script allows the other to work. I have tried using jQuery noconflict, but it did not resolve the issue. H ...