Unable to generate a JSON string from the JavaScript object

I need help converting the object I receive from the server into a JSON file for use in a d3.js chart:

data = {
   "dog ":"5",
   "cat ":"4",
   "fish ":"12",
}

The desired output is:

{    
    "name" : "animal",
    "children" : [
        {"name":"dog", "value": 5},
        {"name":"cat", "value": 4},
        {"name":"fish", "value": 10}
    ]
}

This is what I have so far:

   var jsonText = [] ;
   for ( key in data) {
      jsonText.push({name : key.trim(), value : parseInt(data[key])});
 }

However, when I try to print out the object, I get:

[object Object],[object Object],[object Object]

I am also unsure how to add other attributes to the JSON file. Any suggestions would be greatly appreciated.

Answer №1

If you want to create a specific object structure, you can utilize the Object.keys(data) method in JavaScript and iterate through each key to achieve your desired result.

var data = {
 "dog ":"5",
 "cat ":"4",
 "fish ":"12",
};
var res = {
  category: "animal",
  details: []
};
Object.keys(data).forEach((key)=>{
  res.details.push(
   {name:key.trim(), quantity: parseInt(data[key])}
  );
});

console.log(res);

Answer №2

You're almost there (the array is correctly formatted), but the final array should be assigned to the children property of the object. Using Object.entries and map would make it simpler to transform one array into another based on the same elements:

const data = {
   "dog ":"5",
   "cat ":"4",
   "fish ":"12",
};
const children = Object.entries(data)
  .map(([name, value]) => ({ name: name.trim(), value: Number(value) }));
const output = { name: 'animal', children };
console.log(output);

Answer №3

If you are manually inserting a key such as animal, this code snippet should function properly and the values should be integers.

var data = {
   "dog ":"5",
   "cat ":"4",
   "fish ":"12",
}

var children = Object.keys(data).map((key) => {
  return {
    name: key.trim(),
    value: parseInt(data[key])
  }
})

let result = JSON.stringify({
  name: 'animal',
  children
})

console.log(result);

This code will output:

{"name":"animal","children":[{"name":"dog ","value":5},{"name":"cat ","value":4},{"name":"fish ","value":12}]}

Answer №4

Experiment with -

console.log(JSON.stringify(jsonText))

Answer №5

Initialize an object with the key children and add values to it

const animalsData = {
  "dog": "5",
  "cat": "4",
  "fish": "12",
}

const newObj = {
  "name": "animal",
  "children": []
}
for (let keys in animalsData) {
  newObj.children.push({
    name: keys.trim(),
    value: parseInt(animalsData[keys], 10)
  });
}
console.log(newObj)

Answer №6

One possible solution involves the following code snippet:

    const data = {
       "dog ":"5",
       "cat ":"4",
       "fish ":"12",
    }

    Object.keys(data).reduce((obj, animal) => ({
      ...obj,
      children: [
          ...obj.children,
          {
              name: animal,
              value: data[animal]
          }
      ]
    }), {name: "animal", children: []})

    console.log(JSON.stringify(obj))

This approach offers a more streamlined way to achieve the desired outcome.

Answer №7

To loop through the data object, you can use a for..in loop and add key-value pairs as objects to your children array:

const data = {
   "dog ": "5",
   "cat ": "4",
   "fish ": "12",
}

let obj = {
  name: "animal",
  children: []
}

for (prop in data) {
  let animal = {}
  animal[prop.trim()] = Number(data[prop])
  obj.children.push(animal)
}

console.log(JSON.stringify(obj))

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

Can dynamic loading JavaScript be debugged using a debugger such as WebKit, FireBug, or the Developer Tool in IE8?

After asking a question on Stack Overflow, I have successfully written JavaScript functions for loading partial views dynamically. However, debugging this dynamic loading script has been a challenge for me due to all loaded JavaScript being evaluated by th ...

Executing the npm run test command with the unsafe-perm flag within the lifecycle phase

My React/Redux app is working fine, but whenever I run the command below: npm run test An error occurs as shown below: 6 info lifecycle [email protected]~test: [email protected] 7 verbose lifecycle [email protected]~test: unsafe-perm in li ...

Transform your MySQL data into JSON format effortlessly by harnessing the power of PHP,

Code <?php include "dbconfig.php"; include "yrsetup.php"; $tdate='2018-11-19'; $tmarket='sirsi'; $sql="SELECT ALLCODES.NAME AS Type,MIN(LOT1819.RATE) AS Min,MAX(LOT1819.RATE) AS Max,ROUND(SUM(LOT1819.RATE)/COUNT(LOTNO),0) AS avg F ...

Locating the top 3 largest values in an HTML data table and highlighting them in red

Issue Description: I am working with data that displays the electricity consumption of different buildings in HTML tables. There is a possibility that these tables may contain duplicate values. With the use of jQuery, I am seeking a method to identify an ...

Maintain the webpage content even after submitting a form with a file attachment on the same page

I am in the process of creating a secure webpage exclusively for our members. This page will allow members to access their personal data stored in the database and upload files as needed. One concern I have is how to return to the member page with all the ...

Utilizing AJAX to define the attributes of an object

As a beginner in OOP, I am trying to create an object using an ajax request. My goal is to retrieve 'responseArray' in JSON format and then manipulate it. function address(adres) { this.address_string = adres; var self = this; $.ajax({ typ ...

An easy guide to rerouting a 404 path back to the Home page using Vue Router in Vue.js 3

Hello amazing community! I'm facing a small challenge with Vue.js 3. I am having trouble setting up a redirect for any unknown route to "/" in the router. const routes = [ { path: "/", name: "Home", component: Home, }, { path: "* ...

Switch up div containers with JavaScript based on the set array order of elements?

As I work on creating a list that calculates the sum of selected numbers, I encountered an issue with rearranging the items. Despite successful functionalities like adding images with names, changing languages, and performing calculations, the page keeps r ...

Awaiting the completion of the AJAX request before wrapping up the jQuery

I'm troubleshooting a piece of jQuery code that is not working as expected: var newData = checkCP(somedata); if(newData=="hi"){ alert("Welcom"); } function checkCP(jsData){ $.ajax({ type: "POST", url: "Process.php", ...

Ways to discreetly conceal forward and backward buttons in the v-pagination component of Vuetify

Is there a way to remove the previous and next buttons from v-pagination in Vuetify? Here's my code snippet- <v-pagination v-model="page" :length="pageCount" :total-visible="8" color="primary" /> ...

Discovering details regarding cookies established by an external domain

Is it possible to retrieve the host address of the domain that created a cookie on my webpage? Here is the scenario I am facing: I am on "domain A" and have a script linked from "domain B". A method on "domain B" sets a cookie on my "domain A". How can ...

Jest and Enzyme failing to trigger `onload` callback for an image

I'm having trouble testing the onload function of an instance of the ImageLoader class component. The ImageLoader works fine, but my tests won't run properly. Here's an example of the class component: export default class ImageLoader extend ...

How to transition from using a CDN to NPM for implementing the Google Maps JavaScript MarkerClusterer?

Currently integrating Google Maps JavaScript MarkerClusterer from CDN, I am considering transitioning to the NPM version for Typescript checking in my JavaScript files. However, I am encountering difficulties understanding how to make this switch. The docu ...

Mastering the art of manipulating arrays with jquery

Trying to implement a dynamic search bar feature using jQuery. Here is the code snippet: Fiddle : https://jsfiddle.net/fpLf1to4/ var inputSearch = $('.searchInput').hide(); var searchArray = ['s','e','a',& ...

Interactive ajax and php dropdown menu

Hey there, I'm running into a small snag with my dynamic select feature, as mentioned in the title. I am aiming to achieve the following outcome: When a user selects an instrument from the first dropdown menu, the second dropdown menu labeled "Besetzu ...

Need to update React textarea with value that is currently set as readonly

In my React application, I have a textarea that is populated with a specific value. My goal is to allow this textarea to be updated and then submit the form in order to update the corresponding row in the database. <textarea id="description" className= ...

Retrieving the initial element from a JSON data

Having trouble accessing all data elements from the "api_data" in this JSON response. I attempted various methods to retrieve the "api_data" but I am only able to retrieve the first element. It is puzzling why the rest of the data is not appearing in the ...

Input field in a tableview

I have a ListView that features a dropdown, 4 textboxes and buttons. My goal is to only show the fourth textbox (enclosed in a span) when the dropdown value in each row of the ListView is set to 2. For instance, if there are 5 records being displayed in t ...

Pressing the up arrow in Javascript to retrieve the most recent inputs

Is there a way to retrieve the most recent inputs I entered in a specific order? For example: I have an array with 20 elements, and every time I enter something, I remove the first element from the array and add the new input at the end. So, when I press ...

Update: Cannot mark as invalid a nested document that has not been included in an array

I recently encountered an issue with my upsert query in mongoose. It was functioning perfectly in version 3.8, but ever since I upgraded to version 4, I've been facing the following error: Unable to invalidate a subdocument that has not been added to ...