Creating objects with Javascript looping

Here is the JSON data that I am working with:

[
  {
    "name": "sp5",
    "damage": "68",
    "penetration": "35",
    "class1": "6",
    "class2": "6",
    "class3": "6",
    "class4": "5",
    "class5": "3",
    "class6": "2"
  },
  {
    "name": "sp6",
    "damage": "58",
    "penetration": "43",
    "class1": "6",
    "class2": "6",
    "class3": "6",
    "class4": "6",
    "class5": "5",
    "class6": "4"
  }
]

In my function, I iterate over each object in the array and then loop through the properties of that object. The goal is to extract properties from 'damage' to 'class6' and create a new object for each item to be pushed onto the chart.data.datasets array. However, instead of having 8 values in each object's data array, I am ending up with 16.

function createObjectsForChart(data) {
        console.log(`Data: ${data}`);
        const chart = {
          type: 'bar',
            data: {
                labels: ["Damage", "Penetration", "Class1", "Class 2", "Class 3", "Class 4", "Class 5", "Class 6"],
                datasets: [],
            }
          }
          const dataset = {
            label: "",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: []
          }

          let myChart = Object.create(chart);

          data.forEach((item, i) => {
            console.log(`Item: ${item}, Index: ${i}`);


            console.log(`Data length: ${data.length}`);
            //data[i]

            let myData = Object.create(dataset);
            count = 0;
            for (const property in item) {
              if(count >= 1) {

                 
                myData.data.push(item[property]);
              }
              console.log(`Property: ${property}, Value: ${item[property]}`);
              count++;
            }
            myData.label = data[i].name;
            myChart.data.datasets.push(myData);
          });

          
          console.log(myChart.data.datasets);
      }

Answer №1

The issue lies in attempting to generate a deep copy of the dataset variable using Object.create. This method does not produce a deep copy, causing all duplicates to reference a single instance of the data array. One potential solution is to use

Object.assign({}, dataset, {data: []})
as a quick workaround.

Answer №2

var x=[
  {
    "name": "sp5",
    "damage": "68",
    "penetration": "35",
    "class1": "6",
    "class2": "6",'https':'//stackoverflow.com/editing-help',
    "class3": "6",
    "class4": "5",
    "class5": "3",
    "class6": "2"
  },
  {
    "name": "sp6",
    "damage": "58",
    "penetration": "43",
    "class1": "6",
    "class2": "6",
    "class3": "6",
    "class4": "6",
    "class5": "5",
    "class6": "4"
  }
]
createObjectsForChart(x);

function createObjectsForChart(data) {
        console.log(`Data: ${data}`);
        const chart = {
          type: 'bar',
            data: {
                labels: ["Damage", "Penetration", "Class1", "Class 2",
                "Class 3", "Class 4", "Class 5", "Class 6"],
                datasets: [],
            }
          }
          const dataset = {
            label: "",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: []
          }

          let myChart = Object.create(chart);

          data.forEach((item, i) => {
            console.log(`Item: ${item}, Index: ${i}`);


            console.log(`Data length: ${data.length}`);
            
         let myData =   Object.assign({}, dataset, {data: []})
            count = 0;
            for (const property in item) {
              if(count >= 1) {
                myData.data.push(item[property]);
              }
              console.log(`Property: ${property}, Value: ${item[property]}`);
              count++;
            }
            myData.label = data[i].name;
            myChart.data.datasets.push(myData);
          });

          console.log(myChart.data.datasets);
      }

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

Retrieve a JSON response from within a schema housed in MongoDB

I have a document structure that looks like this: { "id": "someString", "servers": [ { "name": "ServerName", "bases": [ { "name": "Base 1", "status": true }, { "name": "Base 2", ...

Basic library using babel, TypeScript, and webpack - Error: (...) is not a recognized function; within Object.<anonymous>

Recently, I encountered a strange issue while trying to bundle a simple function using babel, typescript, and webpack. You can find the example that is not working at this link. To test it, simply download the code, run npm/yarn install, npm/yarn run buil ...

Creating a simulation of a sun-like vector rotating around a sphere in three.js

Currently, I am attempting to modify this code (which was originally based on an implementation found here). While I have successfully achieved the desired visualization and rendering effects, my goal now is to introduce realistic movement into the animati ...

The Adobe Brackets Live Preview feature is currently experiencing difficulty connecting to the Node.js server

I'm encountering an issue while trying to run a Node.js server using Adobe Brackets. When I initiate live preview (with the URL being http://localhost:SOMERANDOMPORT/path/to/file.html), and start the server, typing http://localhost:3000/test into anot ...

Refresh the page once the function has been executed

Recently, I came across a basic javascript code that I need some help with. I want to reload the page after certain elements have faded out and back in. The problem is, I'm not sure where exactly I should include the window.location.reload(); function ...

Skip a single test from a suite in Firefox using Protractor automation framework

I have a collection of tests in my tests folder, all named with the convention ending in spec.js. By using the */spec.js option in the Config file, I am able to run all tests seamlessly. However, I encountered an issue where I needed to skip running a spe ...

Character array termination point

My attempts to display characters on the screen have resulted in multiple errors. Here is an example of one failed implementation: Example 1: #include <stdio.h> int main(int argc, char const *argv[]) { char hello[6] = {'h', 'e&apo ...

Preventing Multiple Form Resubmissions in PHP

I have multiple forms that require navigation from the initial form to the final form. Each form includes both 'NEXT' and 'BACK' buttons for moving forward and backward in the process. I am looking for a way to prevent the confirmation ...

Is there a way to visualize the prototype chain of a JavaScript object?

Consider the following code snippet: function a() {} function b() {} b.prototype = new a(); var b1 = new b(); It can be observed that a has been incorporated into the prototype chain of b. This demonstrates that: b1 is an instance of b b1 is an instance ...

Making a POST request with ajax in Django

I encountered some difficulties while attempting to send a POST request using ajax in Django. I have searched various resources, but have not yet found a solution. Below is the javascript code that I am using, following this guide: $.ajax({ url: &apo ...

What could be causing my React app to consistently reload whenever I save a file in my project?

Hi there, I am currently working on a project using React, GraphQL, Node, and MongoDB. I have been trying to upload images to a folder within my app, but I am facing an issue with the app reloading after saving the file. I attempted to manage a local state ...

Updating an ad unit dynamically in an HTML5 mobile web application through doubleclick DFP refreshing

I am currently working on developing an HTML5 mobile web application. The app loads, initializes, and constructs the user interface. Users can then pull in content through feeds, resulting in a dynamic display of changing content within the existing inter ...

How can I save every attribute of an object, including functions, to a JSON file?

How can I save a Json file with both data and functions included? I have tried using JSONfn, but it doesn't preserve the functions for me. I attempted the following code, but it didn't achieve the desired outcome: fs.writeFile("object.json", ...

Exploring the Differences Between JSON Arrays in Angular 6

I am facing a challenge with two distinct JSON objects. One is as follows: a = [{id:"1",time:"timestamp"},{id:"2",time:"timestamp"},{id:"3",time:"timestamp"},{id:"4",time:"timestamp"},{id:"5",time:"timestamp"}]; b = [{id:"1",time:"timestamp"},{id:"3",tim ...

I'm having trouble with my pagination controls not correctly displaying the next and previous indices. What adjustments should I make to fix this issue?

When a record is clicked in my code, the details are displayed. Within this details section, there are 2 links (previous, next) that allow navigation to the previous and next records. The issue arises when navigating to the next page from pagination – up ...

Ordering an array in a VUEjs template using computed properties

Working with a VUE template, I retrieve an array from an API which contains a list of countries. Now, based on the ID received, I have a requirement to rearrange this array... The code snippet may resemble something like: Vue.component('select-list ...

The efficiency of XSL Template is significantly impacting loading time

Hello there, I am facing a challenge with my webpage's loading speed due to the code provided below. Can you assist me in optimizing it? <xsl:template match="Category" mode="CategorySelectorScript"> <xsl:variable name="ThisCateg ...

Top and bottom selling items in array C++

Currently, I am facing issues with outputting the most and least sold items in an array. The output is either incorrect or blank, and I am struggling to figure out the reason behind it. Each item in the array has a corresponding price, name, and number of ...

"Troubleshooting: Why is TailwindCSS not functioning correctly in my NextJS

My project utilizes a combination of NextJS, TailwindCSS, and Typescript. Strangely, everything displays correctly in the development environment, but once in production, the tailwindcss classes are not being applied. For reference, here is the link to t ...

Retrieve information from the previously selected option in a dropdown menu, along with information from the currently selected option

Dealing with variable scoping in JavaScript can be a bit tricky. I've experimented with various methods like using window.var or declaring variables inside and outside of functions, but nothing seems to work. Here's the scenario: $(".some_field" ...