What is the best way to remove double quotes surrounding "name" and "count" when displayed in the JavaScript console output?

I am struggling to transform the input:

["apple", "banana", "carrot", "durian", "eggplant", "apple", "carrot"] into the desired output:

[{ name: "Apple", count: 2 }, { name: "Banana", count: 1 }, { name: "Carrot", count: 2 }, { name: "Durian", count: 1 }, { name: "Eggplant", count: 1 }], where I seem to be having trouble with this incorrect output:

[{"name":"Apple","count":2},{"name":"Banana","count":1},{"name":"Carrot","count":2},{"name":"Durian","count":1},{"name":"Eggplant","count":1}]. How can I achieve the correct output:

[{ name: "Apple", count: 2 }, { name: "Banana", count: 1 }, { name: "Carrot", count: 2 }, { name: "Durian", count: 1 }, { name: "Eggplant", count: 1 }] using the console.log() method?

    <html>
    <body>
    <script>
    var input = ["apple", "banana", "carrot", "durian", "eggplant", "apple", "carrot"];
    
    var A = 0;//to count the number of apples
    var B = 0;//to count the number of bananas
    var C = 0;//to count the number of carrots
    var D = 0;//to count the number of durians
    var E = 0; //to count the number of eggplants

     for (var i = 0; i < input.length; i++)
      {
         if (input[i] == "apple")
         {   
           A += 1;  
          }
         if (input[i] == "banana")
         {   
           B += 1;  
          }
         if (input[i] == "carrot")
         {   
           C += 1;  
          }
         if (input[i] == "durian")
         {   
           D += 1;  
         }
         if (input[i] == "eggplant")
         {   
           E += 1;  
         }
       }            

    let x1 = { name: 'Apple', 
               count: A };
    let x2 = { name: 'Banana', 
               count: B };
    let x3 = { name: 'Carrot', 
               count: C };
    let x4 = { name: 'Durian', 
               count: D };
    let x5 = { name: 'Eggplant', 
               count: E };

   var output = [];
   output.push(x1);
   output.push(x2);
   output.push(x3);
   output.push(x4);
   output.push(x5);

   console.log("output = ", output);
   document.getElementById('output').innerHTML = JSON.stringify(output);

   </script>
   </body>
   </html>

Answer №1

To change the format of a string, you can utilize regular expressions like so:

var yourStringifiedResult = "[{\"name\":\"Apple\",\"count\":2},{\"name\":\"Banana\",\"count\&\quot;1},{\"name\":\"Carrot\",\"count\":2},{\"name\":\"Durian\",\"count\":1},{\"name\":\"Eggplant\",\"cont\":1}]";

yourStringifiedResult = yourStringifiedResult.replace(/"(\w+)"\s*:/g, '$1:');
console.log(yourStringifiedResult);

Here is a demonstration showing how it works:

var yourStringifiedResult = "[{\"name\":\"Apple\",\"count\":2},{\"name\":\"Banana
 \",\"count\":1},{\"name\":\"Carrot\",\"count\":2},{\"name\":\"Durian\",\"count\":1},
 {\"name\":\"Eggplant\",\"count\":1}]";

yourStringifiedResult = yourStringifiedResult.replace(/"(\w+)"\s*:/g, '$1:');
console.log(yourStringifiedResult);

Answer №2

To display the items in the array, simply append the following code:

let result = "";

for (let item of list) result += "Name: " + item.name + ", Quantity: " + item.quantity + ", ";

document.getElementById('result-display').innerHTML = result;

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

Generate a new perspective by incorporating two distinct arrays

I have two arrays containing class information. The first array includes classId and className: classes = [ {classid : 1 , classname:"class1"},{classid : 2 , classname:"class2"},{classid : 3 , classname:"class3"}] The secon ...

Generating JSON data from a dropdown menu element

I'm working on a web page that showcases information for students in my database. One key field is their birth country, currently stored as the full name of the country. My goal is to convert these full country names into two-character strings. For ex ...

Setting up a Web application testing environment on its own

Embarking on my journey in web application development and testing, I am currently involved in a project that requires me to create a standalone environment for testing the web application. The main goal is to ensure the web application is easily testable ...

Struggling to find your way around the header on my website? Let me give

I'm looking to display certain links prominently at the top of a page, similar to this example: "home > page1 > link1 > article 1." Can someone advise on how to achieve this using HTML, PHP, or jQuery? ...

The `chrome.windows` API is not defined for this particular Chrome

I'm currently in the process of developing a Chrome extension that will allow users to effectively manage open tabs within a specific application's website. Here is the current manifest file: { "manifest_version": 2, "name": "AT Tabs", ...

Problematic Situation Arising from JavaScript AJAX and NVD3.JS Unresolved Object Error

I am currently in the process of developing a script that will allow me to retrieve data for my chart from an external PHP file. Initially, I attempted manually inputting the data into the chart and it worked perfectly fine. However, when I tried using A ...

Dividing the text by its position value and adding it to a fresh object

I needed to divide the paragraph into sections based on its entityRanges. Here is what the original paragraph looks like: { type: 'paragraph', depth: 1, text: 'Do you have questions or comments and do you wish to contact ABC? P ...

Using Django, CSS, and Javascript, create a dynamic HTML form that shows or hides a text field based on the selection

How can I hide a text field in my Django form until a user selects a checkbox? I am a beginner in Django and web applications, so I don't know what to search for or where to start. Any guidance would be appreciated. Here is the solution I came up wi ...

The error message "mapboxgl is not defined" indicates that the mapboxgl variable

I have been encountering the following error message in the console, and despite spending hours trying to troubleshoot it, I have been unsuccessful in resolving the issue. Could someone assist me in fixing this problem? error image I am having difficulty ...

Having issues with passing data to a Modal on eventClick using FullCalendar with ReactJS, receiving a "cannot read property of undefined" error. Any advice on how

My MERN stack application utilizes the FullCalendar plugin, even though I am aware that mixing jQuery with React is not ideal. Unfortunately, I am a novice developer and running behind schedule. The goal is to allow users to click on an event on the calen ...

JavaScript: A guide to substituting specific characters in a string

I attempted to extract a list of names from a URL as URL parameters. var url_arrays = [],url_param; var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < url.length; i++) ...

Is it possible to asynchronously access a JSON object that has been retrieved from a local file on a global scale using the XMLHttpRequest method and

Having some trouble manipulating data from a local JSON file using this technique (no jQuery) as I can't seem to access the object on a global scale: var actual_JSON; function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.o ...

Struggling with repeatedly traversing characters in a string to solve the Palindrome challenge

I am working on a recursive solution for a Palindrome problem, but it seems that my code is only considering the first recursive call instead of the second one which should analyze all characters in the string. I suspect there might be a logical error in ...

Strategies for accessing a collection of DOM elements in React

Currently, I'm embarking on a challenge to complete 50 projects in 50 days by Brad Traversy. However, I've decided to take it up a notch by building them in Next.js with React since that's what I work with professionally. Unfortunately, thi ...

Is there a seamless way to effortlessly upload massive files to s3 through an adminjs dashboard without encountering any glitches?

Attempting to upload large files (40mbs+) to s3 using the @adminjs\upload feature on the adminJS dashboard. While testing locally, most files are successfully uploaded but it takes a considerable amount of time. However, when attempting this on the AW ...

How to trigger an Angular (ionic) view update following an HTTP post request

Is there a way to update the expression in my view after making an HTTP post request? I have tried using the $scope.$apply function, but it gives me an error from ionic.bundle.js saying "$digest already in progress". Could this be a mistake on my part or ...

How can I use Angular's $filter to select a specific property

Is there a convenient method in Angular to utilize the $filter service for retrieving an array containing only a specific property from an array of objects? var contacts = [ { name: 'John', id: 42 }, { name: 'M ...

Turbolinks gem causing ShareThis to malfunction

After adding the turbolinks and jquery-turbolinks gems to my project, I noticed that my ShareThis button no longer pops up when clicked. The ShareThis scripts currently included in my application.html.erb head are: <script type="text/javascript">va ...

Calculating the total number of clicks on a button using PHP

I am attempting to track the total number of clicks on a button by individual users, rather than combining all members' clicks. Each user's clicks on the button should be logged separately. I am struggling to determine the best approach for this ...

Should I install @capacitor/android as a dev dependency in the package.json file of a React project?

I was pondering whether it would be better to add @capacitor/android, @capacitor/ios, and @capacitor/core as development dependencies. ...