Converting a JavaScript object into JSON format

I am currently working on serializing a JavaScript object to JSON. Here is the code I have written so far:

var info = {};

...

$.each(data, function (key, value) {
           info["name"] = value.name;
            info["id"] = value.id;
                        });
...

console.log(JSON.stringify(info));

However, the output I receive is : {}

If anyone has suggestions on how to achieve the desired output like the one below, it would be greatly appreciated:

[{name: "John", id: "1"},
 {name: "Anna", id: "2"},
 {name: "Peter", id: "3"}]

Thank you.

Answer №1

To successfully complete the task at hand, you should:

  • Transform your info variable into an array instead of a JSON object.

Revise your code as follows:

let infoArray = [];

$.each(data, function (key, value) {
         infoArray.push({
             name: value.name,
             id: value.id
         });
});

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

converting an angular object into a string representation

I stumbled upon this guide: . and it includes the following piece of code: import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl ...

Is it possible for me to add images to the input file individually before submitting them all at once?

When images are inserted one by one, the 'input file' only reads one picture at a time. However, when images are inserted in multiple quantities, the result is displayed for each image that the user inputs. window.onload = function() { //Ch ...

"Running 'npm run build' in Vuejs seems to have a mind of its own, acting

Recently, I completed a project and uploaded it to Github. The issue arises when I attempt to clone it to my live server - only about 1 out of 10 times does everything function correctly after running npm run build. My setup consists of Ubuntu 16 with ngin ...

Binding Data in Vue Multiselect

After extensive searching, I stumbled upon an amazing searchable select Vue component that has caught my eye: https://github.com/monterail/vue-multiselect. However, there seems to be a small issue when it comes to feeding it an array of objects as options ...

Use a conditional statement for each element within the array

Below is the code I am currently using: if (res[0].toString() == "hello") { res[0] = "string"; }; While it works, I would like this logic to apply to all elements rather than just the first one. Is there a way to achieve this for every element in the ar ...

Consistently obtaining the same outcome in JavaScript, always

Is it possible to resolve this issue? I keep getting a result of less than 18 when trying numbers 1-100, even though the output should be for values under 18. In my HTML code, there is a <p> element with id="result", an input with id=&quo ...

Rejuvenating a template generated on the server in AngularJS

I have a specific partial which is a report - simply a static list of names and dates designed for viewing and printing purposes. For efficiency reasons, the report is rendered server-side, so when a report request is made, my API responds with HTML rathe ...

Obtain the URL for making an asynchronous request using PHP and SQL

I'm encountering some issues with a website I am attempting to update. A script named "jquery.script.js" is called in the head section containing some code. $.ajax({ url: 'function.js.php?option=urlget&id='+movie_id, ...

Add opening and closing HTML tags to enclose an already existing HTML structure

Is there a way to dynamically wrap the p tag inside a div with the class .description-wrapper using JavaScript or jQuery? This is the current html structure: <div class="coursePrerequisites"> <p> Lorem ipsum.. </p> </ ...

How can I show/hide a div based on checkbox click on my website? It works in jsFiddle, but not on my actual site. Any suggestions?

Is there a way to show or hide a div based on a checkbox click? I've got it working in jsFiddle, but for some reason, it's not functioning properly on my website. Any thoughts on how to fix this? My goal is to offer multiple payment methods (cre ...

jQuery fails to fetch information

I am currently working with a straightforward script as shown below: $(function() { var url = theme_directory + '/func/api.php'; $.get( url, function(data) { alert("Data Loaded: " + data); }); }); Here is the code for api ...

.then function not functioning properly in Axios DELETE request in a React project

I am currently facing an issue with calling a function to update the array of notes after deleting a note from the database. The function causing the error is called deleteNote, and the function I intend to call within the .then promise is getNotes. Here i ...

Create custom error messages for loopback instead of using the default ones

I am attempting to customize the default error messages provided by loopback. Here is my approach: server/middleware.json: { "initial:before": { "loopback#favicon": {} }, "initial": { "compression": {}, "cors": { "params": { ...

Conceal the Div containing the specified class

I was hoping to hide the first DIV if the second DIV is displayed on the front end, and vice versa upon page load. If the first DIV is set to 'block,' then the second DIV should be set to 'none.' And If the second DIV is set to &apos ...

Converting a Plain Old Java Object (POJO) with a slash in the variable name into JSON format

Using Jackson to convert a POJO to JSON presents a challenge. The desired JSON structure is as follows: "paragraphs": [ { "text": "This is a test text", "page/pages": "1/56", } In the example above, one of the items is named "page/pages". How ...

Scroll to the top of jQuery DataTables when clicking pages in a random order from the bottom to the top and

In my current project, I am working with jQuery Datatables and I need to customize its default behavior. Currently, when I navigate to page 61, the page scroll remains at the bottom of the page. However, if I then click on a lower page number like 60, th ...

iOS experiences a lag in loading dynamic images

I have created a unique jquery carousel specifically designed for mobile devices. It features three containers that display three images at a time, with jquery handling the animation. By detecting the user's swipe direction (left or right), I update t ...

What could be causing my Angular.js application to malfunction on IE7?

I have developed an Angular.js application that is working well on most browsers, but I am now facing compatibility issues with IE 7 and above. I have tried different approaches such as adding id="ng-app", using xmlns:ng, manually bootstrapping angular wi ...

Problem with Google's PageSpeed Insights - Focus on Making Most Important Content Visible

During the process of creating a comprehensive website for a client who has a strong affinity towards Google tools and recommendations, I have encountered an interesting challenge: Despite my best efforts, I seem unable to attain a flawless score for the ...

Utilizing Firebase push notifications with multiple google-service.json files within a single Android Studio project

In a scenario where we have a single project but require multiple Firebase push notification and google-server.json files, how can we effectively manage these multiple files within Android Studio? ...