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

Why is useEffect being executed twice?

For some reason, when I try to run useEffect for the first time page load, it ends up running twice. I can't seem to figure out why this is happening. Can someone please provide assistance? I'm currently using React 18 and I need help understand ...

How can I access the parent elements within a recursive directive?

I'm currently implementing a recursive directive called https://github.com/dotJEM/angular-tree to iterate through a model structure like the one below: $scope.model = [ { label: 'parent1', children: [{ ...

Develop a JSON ping that returns either a true or false response

Currently, I am utilizing Node-RED with the "node-red-node-ping" to ping the IP address 192.168.0.71. The response received is structured as follows: 192.168.0.71 : msg : Object object payload: 0.376 topic: "192.168.0.71" _msgid: "f766d646.764dc8" In cas ...

The Click Event Is Triggering Even with Correct Callbacks Being Set

I am struggling to understand why these functions are not executing properly. I know the correct syntax for binding a function, like this: $('#idOfThing').bind('click', foofunc); function foofunc() { ///do things } However, I am facin ...

Utilizing React and Material-UI to create an autocomplete feature for words within sentences that are not the first word

Looking to enable hashtag autocomplete on my webapp, where typing #h would display a menu with options like #hello, #hope, etc. Since I'm using material-ui extensively within the app, it would be convenient to utilize the autocomplete component for th ...

In Django, the Ajax function will fail to execute if any of the required input fields are left empty

I'm currently using an AJAX function that works well when values are entered for all three fields: pname, psection, and rinput-json. However, it fails to work if any of these fields are left empty. <script type="text/javascript"> funct ...

Exchange SMS messages between server and web application

I'm currently based in Kenya and finding the pricing of Twilio to be quite high. My goal is to send and receive SMS messages, save them in a database, and showcase them on a web app. Do you think it's possible to create this using node.js? What w ...

Transfer the Vue query parameter from the current route to the router-link

Why is it so challenging to detect and pass query parameters in Vue components? I'm trying to access the router from my component, but nothing seems to be working. How can I achieve this? <router-link :to="{ path: '/', query: { myQue ...

The setInterval() function is not functioning properly when used with PHP's file_get_contents

Currently, I'm encountering an issue while attempting to use the function get_file_contents() within a setInterval(). The objective is to continuously update some text that displays the contents of a file. Below is the code snippet: <script src="h ...

Identifying the specific filter used in Vue-tables-2

Trying to configure a basic server-side vue-tables-2 with dual filters - one dropdown and the other a search field. The challenge here is identifying which filter was applied within the requestFunction() in order to send a server request. My current strate ...

When parsing a DateTimeOffset object, it is necessary to include timezone data

My current challenge involves validating data obtained from an API endpoint where users must input a DateTimeOffset. To address this issue, I have developed my own JsonConverter implementation to ensure the DateTimeOffset is in the correct format. Despite ...

How can I replace any non-alphanumeric characters in a string with an underscore using JavaScript or TypeScript?

There is a unique string generated from an external data source that I cannot manage. The system above me necessitates the IDs to adhere to this rule: "Field names should start with a letter and can solely consist of letters, numbers, or underscores (&apos ...

Using Javascript to dynamically populate dropdown options based on radio button selection

I am in the process of developing a basic form that allows users to input the frequency of a specific report. Initially, users were only able to enter days of the week. However, due to changes in demand for certain reports, options such as workday and day ...

modal failing to populate values within control elements in modal

Encountering an issue where the code is calling a Modal, but upon loading it fails to populate the controls with values sent into the JavaScript. No errors are thrown, yet all controls remain empty. As a newcomer to AJAX and JavaScript, I suspect there mig ...

Having trouble getting a new input box to be added when clicking with AngularJS?

I am facing an issue with adding dynamic form fields to the database using PHP. I have utilized angular for this purpose, but only the last form field is getting inserted into the database. To address this, I attempted using arrays and loops to increment a ...

"Experiencing difficulties deploying Firebase functions - Encountering an error message stating 'Cannot read property 'firebase-admin' of

I'm currently facing an issue during the deployment of my Firebase functions and I am seeking assistance to resolve it. While the deployment itself appears to be successful, I keep encountering the following error: Cannot read property 'firebas ...

Guide on creating a project for developing an npm package

Within my git root project, I am utilizing a git subproject called UIComponents. For instance, my main project is named MyApp and the subproject is UIComponents. Currently, I have cloned the UIComponents repository inside my project folder and added UIComp ...

Cheerio - Ensure accurate text retrieval for selectors that produce multiple results

Visit this link for more information https://i.stack.imgur.com/FfYeg.png I am trying to extract specific market data from the given webpage. Specifically, I need to retrieve "Sábado, 14 de Abril de 2018" and "16:00". Here is how I did it using Kotlin an ...

Using Angular 2: A Beginner's Guide to Navigating with the Latest Angular 2.0.0-rc.1 Router

As I embarked on a new Angular 2 project, I was puzzled to discover that I inadvertently installed two different versions of the angular router: "@angular/router": "2.0.0-rc.1", "@angular/router-deprecated": "2.0.0-rc.1", Despite my best efforts, I co ...

Using parseFloat in JavaScript for German number formatting

Currently, I am working on incorporating a Vue.js component that is inspired by the example provided in this link: https://jsfiddle.net/mani04/bgzhw68m/. This is the structure of my source code: computed: { displayValue: { get ...