Exploring various object types in Javascript with JSON

Below is the code snippet I am using to generate an object:

var data = [];
data.push('{"headers":["Category 1","Value 1","Value 2"],"rows":[');
for (var i in results.data)
{
    entry = '["'+ results.data[i].Type +'", '+ results.data[i].Amount +', '+ results.data[i].Discount+'],';
    data.push(entry);
}
data.push(']}');

The desired object I want to create looks like this:

var my_data= {"headers":["Category 1","Value 1","Value 2"],"rows":[["Item A",174,23],["Item B",502,17],["Item C",242,37]...and so on]};

Is there a way to create the object directly without converting it to a string?

Answer №1

Commencing from the data in results.data, you have the ability to reorganize elements and construct fresh Objects without navigating through the chaos of Strings.

Employ Array.map() function to transform the server response into the intended rows array, then create a new Object:

const results = {
  data: [{
      Country: "Australia",
      Price: 174,
      Discount: 23
    },
    {
      Country: "Canada",
      Price: 502,
      Discount: 17
    },
    {
      Country: "France",
      Price: 242,
      Discount: 37
    }, {
      Country: "Germany",
      Price: 102,
      Discount: 42
    }
  ]
}

const rows = results.data.map(row => [row.Country, row.Price, row.Discount]);

var newData = {
  "headers": ["Dimension 1", "Metric 1", "Metric 2"],
  "rows": rows
};

console.log(newData);

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

Using React.js to compute dates based on user-inputted dates

Today was dedicated to tackling the coding challenge of creating a function. I'm currently working on a react app using the PERN stack. The form I'm working on includes multiple date inputs, with two date columns and a total days column. My goal ...

Learning the process of dynamically binding an id to an HTML tag in Vue.JS

I am currently utilizing Bootstrap Vue for UI and attempting to implement a collapsing feature using this provided link For instance, using v-b-toggle.collapse-2 where the 2 represents a static id. However, I am interested in dynamically assigning this id ...

As you scroll, a box blocks off half of the screen

Hey everyone, I could really use your assistance! I'm working on developing a javascript code and here is the idea - if anyone can contribute to it. It's like a social media platform where users enter the site and the is_user_logged_in parameter ...

Whenever I attempt to install json-server using npm install -g json-server, I consistently encounter an error

View image of the persistent error here Despite multiple attempts, I continue to encounter this error. Despite trying different solutions such as clearing the node cache and reinstalling node.js, the issue persists. Strangely enough, running it with admin ...

Encountering an error while trying to implement a React Higher Order Component (HOC): the type provided is invalid – it should be a string or a

Today marks my first experience using Flow in a professional setting, as I typically lean towards TypeScript over Flow. I am encountering an issue while trying to create a simple HOC (Higher Order Component), something I have done numerous times without a ...

Tips for displaying ajax search results in Laravel views

My attempt to send a JSON response via AJAX to my Laravel view is not yielding any successful results. public function viewMasakanAjax(Request $request) { if($request->ajax()) { $alberMasakan = Masakan::where('alber_nama_masakan&ap ...

Ways to determine if an image has a designated width/height using JavaScript (jQuery)

Similar Question: How can I retrieve the height and width of an image using JavaScript? Typically, we can determine the image width using $('img').width() or $('img').css('width') when a width is specified as shown below ...

Is it possible to conceal or disregard text elements from the web browser search function by using CTRL+F?

I have a complex web application interface with a dedicated area for content display. Is there a way to ensure that when users utilize the browser's text search function (CTRL+F), the UI elements are ignored and only the actual content is searched? ...

Best method for connecting user input with a class

I'm currently working with a WYSIWYG editor (Tinymce) that allows users to post YouTube videos. In order to make the video content responsive, I need to add the class "video-container" around any "iframe" tags inserted when users paste a YouTube link ...

Why does my express POST request result in an empty req.body in Node.js?

After confirming that my data is being passed correctly and the db connection is successful, I am facing an issue with my ajax request. Even though the success callback returns the id, my data seems to not be passing through properly. When attempting to a ...

Implementing the rendering functionality in Vuejs 3 to activate the parent component method from its child

Is there a way to call the clicked method on app2 from within ComponentA? Let's explore how this can be achieved in the provided example. const app = Vue.createApp({}); app.component('ComponentA', { template: `<button @click="cl ...

Error message: Vercel is unable to locate the module or its corresponding type declarations when running the command "npm run build"

I've encountered a problem with various components similar to this one. When I run "npm run build" on my computer locally, everything runs smoothly. I have tested node versions 14, 16, and 18 on Vercel, but unfortunately, the issue persists. This is ...

Using Angular ng-token-auth to post to an incorrect localhost address

I have a Node.js server running on http://localhost:3000/, and a React Frontend running on http://localhost:8000/. I am setting up the user authentication feature with JWT. However, when posting the token, it goes to the incorrect localhost address: http ...

Troubleshooting issue with Vue.js FullCalendar v5 component - events not showing up

After upgrading our FullCalendar component in a Vue.js project from version 4.4.2 to version 5.9.0, we encountered issues with events not displaying. Despite building a new calendar step-by-step in a fresh file in an attempt to troubleshoot, the events sti ...

Adjust the value of a select box to the chosen option using JQuery

Could someone please assist me with this code? I am trying to adapt it for use on my mobile device with jQuery Mobile. var obj = jQuery.parseJSON(finalresult); //alert(obj); var dept = '2'; $(document).ready(function () { //$("#opsContactId ...

How can I handle a 404 error if an object is not found in a JSON file?

Below is my code snippet where I check for the correct req.path and display specific text. However, I now need to show a 404 not found error message. I attempted placing it inside the for loop condition with break;, but it's not quite working as expe ...

Ensure that variables are accessible to asynchronous calls without the use of closures

As a newcomer to the world of javascript, I've been trying to navigate the realm of nested functions. Let's explore the following two examples: // example 1 var x = 45; function apple(){ var y = 60; setTimeout(function(){ console ...

Optimizing jQuery UI autocomplete choices through filtering

Currently utilizing the jqueryUI autocomplete feature on my website. Let's say I have the following entries in my database... apple ape abraham aardvark Upon typing "a" in the autocomplete widget, a list appears below the input field displaying the ...

"Vue.js and Node.js have been successfully installed, with their respective versions displayed. However, the applications are

kirti@kirti-Vostro-14-3468:~/flipbook-vue$ node --version v17.6.0 kirti@kirti-Vostro-14-3468:~/flipbook-vue$ vue --version @vue/cli 5.0.1 kirti@kirti-Vostro-14-3468:~/flipbook-vue$ npm run serve > <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Can an HTML, CSS, and Javascript combination be used to create a sidebar addon for LibreOffice?

Is it possible to create sidebar add-ons for LibreOffice/OpenOffice using HTML, CSS, and Javascript? Alternatively, could we utilize the UNO API and an embedded browser to run a web app within LibreOffice for seamless interaction? We have already develope ...