Every time I try to add a new element to my object, I end up with a bunch

I am currently working with an array object that contains similar values. I have been able to successfully filter out the duplicate values using a loop and then add the unique values to another object called objectProperties. Everything seems to be working fine, except for the fact that I am getting NULL values inside the category property.

   // Here is the data I'm extracting
var data = [ 
   {
      "label":"May 14",
      "value":56714.4,
      "proID":"ISB"
   },
   {...} - additional data entries ...
];

var propertiesObject = {    // This is my object
    type: 'mscolumn2d',
     renderAt: 'chart-container',
     width: '1000',
     height: '500',
     dataFormat: 'json', 
     dataSource: {
        chart: {
            caption: "Kilos per Date Comparison"
          
            }, 
    categories: [
            {
                category: [] 
            }
        ]
    }
};
 
    var propCount = Object.keys(data).length; 
    var checkSameLabel = data[0].label;   
    var firstIndex = {"label":data[0].label}; 
    propertiesObject.dataSource.categories[0].category[0] = firstIndex; 
    var currentProject = data[0].proID, counterCurrentProject = 0;
    for(let i = 0; i < propCount; i++) {
        if(checkSameLabel !== data[i].label) { 
            
            const value = data[i].label;
            var obj = { 
                "label": value  
            };
            propertiesObject.dataSource.categories[0].category[i] = value; 
        }  
        checkSameLabel = data[i].label; 
    }
    console.log(JSON.stringify(propertiesObject));
    document.getElementById("result").innerHTML = JSON.stringify(propertiesObject);
<div id="result"></div>

The expected output should look like this inside the "category" section:

{ "label": "May 14" },
{ "label": "May 15" },
{ "label": "May 16" },
{ "label": "May 17" }

However, I seem to be encountering some issues with NULL values due to my loop implementation or possibly some other mistake in the code.

Answer №1

It's better to use push instead of assigning to array indices to avoid empty values:

// sample data extraction
var data = [{
    "label": "May 14",
    "value": 56714.4,
    "proID": "ISB"
  },
  // more data entries...
];

var propertiesObject = { 
  type: 'mscolumn2d',
  renderAt: 'chart-container',
  width: '1000',
  height: '500',
  dataFormat: 'json',
  dataSource: {
    chart: {
      caption: "Kilos per Date Comparison"
    },
    categories: [{
      category: []
    }]
  }
};

var propCount = Object.keys(data).length; 
var checkSameLabel = data[0].label;
var firstIndex = {
  "label": data[0].label
};
propertiesObject.dataSource.categories[0].category[0] = firstIndex; 
var currentProject = data[0].proID,
  counterCurrentProject = 0;
for (let i = 0; i < propCount; i++) {
  if (checkSameLabel !== data[i].label) { 

    const value = data[i].label;
    var obj = {
      "label": value
    };
    propertiesObject.dataSource.categories[0].category.push(obj);
  }
  checkSameLabel = data[i].label; 
}
console.log(propertiesObject);
<div id="result"></div>

You can also simplify the process using a Set to track added labels and iterating over the data with forEach:

// sample data extraction
var data = [{
    "label": "May 14",
    "value": 56714.4,
    "proID": "ISB"
  },
  // more data entries...
];

var propertiesObject = { 
  type: 'mscolumn2d',
  renderAt: 'chart-container',
  width: '1000',
  height: '500',
  dataFormat: 'json',
  dataSource: {
    chart: {
      caption: "Kilos per Date Comparison"

    },
    categories: [{
      category: []
    }]
  }
};

const labelsAdded = new Set();
data.forEach(({ label }) => {
  if (labelsAdded.has(label)) {
    return;
  }
  labelsAdded.add(label);
  propertiesObject.dataSource.categories[0].category.push({ label });
});
console.log(propertiesObject);

Alternatively, you can make use of a Set for label strings and then utilize .map:

// sample data extraction
var data = [{
    "label": "May 14",
    "value": 56714.4,
    "proID": "ISB"
  },
  // more data entries...
];

var propertiesObject = { 
  type: 'mscolumn2d',
  renderAt: 'chart-container',
  width: '1000',
  height: '500',
  dataFormat: 'json',
  dataSource: {
    chart: {
      caption: "Kilos per Date Comparison"

    },
    categories: [{
      category: [...new Set(data.map(({ label }) => label))].map(label => ({ label }))
    }]
  }
};
console.log(propertiesObject);

Answer №2

There seems to be a couple of errors

  1. You created the variable 'obj', but you are not using it

var obj = { 
    "label": value  
};

// Not recommended
propertiesObject.dataSource.categories[0].category[i] = value;

// It should be this, but still incorrect, see point (2)
propertiesObject.dataSource.categories[0].category[i] = obj;
  1. You are adding elements to an array by setting it with an index, you should use array push instead
// Not recommended
propertiesObject.dataSource.categories[0].category[i] = obj;

// Should be
propertiesObject.dataSource.categories[0].category.push(obj);

// Data that I am extracting
var data = [ 
   {
      "label":"May 14",
      "value":56714.4,
      "proID":"ISB"
   },
   // Other data entries go here...
];

var propertiesObject = {    // My object
     // Object details go here...
 };
 
 // Code continues below... 
<div id="result"></div>

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

Struggling to find the right strategy for obtaining real-time data while implementing customized filters

After spending a week scratching my head and experimenting with different approaches, I'm hoping to find some help here... I am working on an application that needs to provide real-time data to the client. I initially considered using Server-Sent-Eve ...

What could be the reason for the absence of this retrieved data in my HTML code?

I have a situation where I am retrieving data from a Parse database and showing it on my template: JavaScript Code: angular.module('yoApp') .controller('downloadsCtrl', function($q, $scope, $rootScope, $http, appService, serviceUplo ...

Adjust the size of various texts to fit the width of the container

I have a unique challenge with resizing text to fit within specific elements. The texts may vary in length and I want to ensure that the longest line fits perfectly within the container's width. For example, consider this code snippet: .container ...

Error: Unable to locate Vue and its definition

Currently in the process of revamping my portfolio and transitioning it to Vue. This marks my second endeavor with Vue, however, I'm encountering an issue where I continuously receive an error stating that Vue is not defined in my main.js file (which ...

Swapping a value within an array and moving it to a new position

Consider this scenario: I am dealing with a list of arrays containing values like: let data = [ "10-45-23:45", "10-45-22:45", "10-45-20:45", "10-45-23:45", "10-45-23:59,00:00-04:59", "10-45-23:59, 0 ...

Choose the designated radio button option automatically depending on the value received from the server

In the process of creating a quiz engine using angularjs, I have successfully loaded questions with options and implemented the NEXT and BACK buttons. However, I am facing a challenge with pre-selecting the previously chosen option when the user clicks the ...

Obtain the response body in Nest JS middleware

Currently, I am working on developing logging middleware for my project. My main goal is to log the response body specifically in 500 responses. However, I have encountered an issue where the response body is not present in the Response object when using a ...

What are the steps to resolve a Fetch request issue with a Node.js server?

I am attempting to make a simple POST request using the fetch method. I am working on building a contact form using Vanilla Javascript, HTML, and CSS on the front end, while utilizing Node.js / Express on the backend. Take a look at my front end code: ...

Guide on making a PDF input field function like a regular input field with PDF.js

Whenever I encounter input fields in a pdf file, I attempt to use pdf js to interact with them. However, I have been facing challenges in doing so. Allow me to provide an example of my objective: const canvas = document.getElementById(`canvas-${this.page ...

What steps can be taken to avoid or halt focusing on the following input text element?

I came across a situation where I have to focus on the h1 element of an overlay instead of moving to the next tabbable element. The overlay appears after a service call triggered by blur event from the first input text field. Every time the blur event is ...

The app's functionality is disrupted by a malfunctioning Appframework jQuery

Having some trouble implementing the jQuery UI autocomplete widget in a PhoneGap app using the jq.appframework.js plugin. Here is how I have included the necessary scripts and styles: <script src="appframework/jquery.js"></script> <script s ...

Struggling with modifying background color in Vue.js?

My intention is to make the landing page background color orange, but I'm encountering an issue where all pages end up with the same color. I attempted to use scoped on the landing page to target only that specific page, however, it resulted in the e ...

Error in NextJS: The module 'caniuse-lite/data/features/css-unicode-bidi' could not be located

Issue encountered during the build process. Error: Module 'caniuse-lite/data/features/css-unicode-bidi' not found Attempted to include "caniuse-lite": "^1.0.30001281" and "^1.0.30001390", but the problem persists. ...

Trigger the oninput event using jQuery

I am using an oninput event on a textarea to dynamically adjust its height based on user input. However, I've encountered an issue when trying to edit the value programmatically using jQuery's val() function: it does not trigger the oninput event ...

Performing Ajax requests according to the selected checkbox data

Hey, I'm just starting out with Jquery and Ajax and could use some help to solve my issue. Currently, I am populating checkboxes based on my model values and making an ajax call to get a list of countries for each selected value. Now, I want to chan ...

Searching for an element with a changing name using jQuery - Struggling with quotes

Looking to navigate my DOM based on the value of an option in a select box. The value of "searchkey" can vary based on user input, for example: searchkey = dell'anno searcheky = dell"anno These options, particularly the first one, can cause issues ...

JSON retrieving a singular record exclusively

I am facing a dilemma with my code. When using a certain function, I retrieve hundreds of records but I am unable to add any additional information. Here is the code snippet: function(data){ $.each(data.products, function(i,item){ ...

Tips for ensuring that the headers remain fixed in both the horizontal and vertical directions while allowing the data

I have been trying to create a table with a fixed header (meaning the header must be visible both vertically and horizontally). The table should be scrollable It should have a horizontal header The vertical header should match the horizontal header When ...

I have a JavaScript code stored as a string that I need to transform into plain JavaScript

If I have a variable in string format, for example suppose there is a JavaScript code inside it: var string="function myFunction(a,b){return a*b;}"; I want to convert this into pure JavaScript code format like so: function myFunction(a, b) { return ...

What steps do I need to take to implement a unique second factor of authentication using Firebase?

Looking to enhance the security of my application, I aim to offer my users the option to implement a second factor of Authentication. Currently, I am utilizing Firebase for user logins and registrations, which supports a second factor through SMS verificat ...