Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data.

When I try to directly set the values, I get an undefined result. So I created a variable to store values first and then attempt to pass it to labels and data.

My question is, how can I dynamically set values for labels and data from the dataList array?

    this.dataList = [['label1', 200], ['label2', 300], ['label3', 500]];

// I want to access all labels to label, all numbers to data in below instead of using static data, I want to fetch data from the dataList array

    this.data = {
    labels: ['label1', label2, label3],
    datasets: [
      {
        data: [200, 300, 500],
        backgroundColor: [
          "#FF6384",
          "#36A2EB",
          "#FFCE56"
        ],
        hoverBackgroundColor: [
          "#FF6384",
          "#36A2EB",
          "#FFCE56"
        ]
      }]
  };

Instead of hardcoding values in labels and data, I aim to populate them with dynamic data stored in the dataList array.

Answer №1

If you want to achieve this, you can make use of JavaScript's Reduce function.

Check out the Stackblitz DEMO - feel free to modify the this.dataList variable and observe the dynamic output changes.

this.dataList = [['lable1', 200], ['lable2', 300], ['lable3', 500]];

this.data = {
  labels: this.dataList.reduce((result, item) => {
    result.push(item[0]);
    return result;
  }, []),
  datasets: [
    {
      data: this.dataList.reduce((result, item) => {
        result.push(item[1]);
        return result;
      }, []),
      backgroundColor: [
        "#FF6384",
        "#36A2EB",
        "#FFCE56"
      ],
      hoverBackgroundColor: [
        "#FF6384",
        "#36A2EB",
        "#FFCE56"
      ]
    }]
};

Answer №2

To ensure that the labels match the elements in the dataList:

labels: dataList,

If you prefer to prevent any changes to the original data:

labels: dataList.slice(),

Another option is to use the spread operator:

labels: [...dataList],

Answer №3

To ensure that your code runs correctly, place it within the .subscribe() function block. This is necessary because the operation is asynchronous and you must wait for the data to be retrieved before proceeding. Within this block, simply assign values to variables for labels and datasets. While I have utilized es6 syntax in this example, feel free to use whichever version suits your needs.

dataList: Array<any> = [];
data: any = {}; //Set an initial value for data
searchCond: SearchConditions;

constructor(private apiService: ApiService) {

this.searchCond = new SearchConditions();
this.searchCond.eventType = "encounterType";

this.apiService.getEncounterDashBoard(this.searchCond)
  .subscribe(data => {
    this.dataList = data.result;
    let [labels, datasets] = this.dataList; 
    this.data = {
      labels: labels,
      datasets: 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 the information in a div element from an external website by utilizing AJAX

Exploring the world of AJAX is new to me, and I am eager to fetch content from a div on an external site and display it on my own website. Below is the current code snippet I have: <html> <head> <script src="https://ajax.googleapis.com ...

Is there a way to retrieve data from both JSON and a file simultaneously?

I'm trying to use JavaScript fetch API to upload a photo message with text to Discord webhook. How can I upload both my JSON data and file? var discordWebHookBody = new FormData() discordWebHookBody.append("map", map) discordWebHookBody.appe ...

Encountering an issue with double quotes formatting in Spring Boot applications

Currently, I am developing an application where I need to pass data from a Spring Boot controller to a template using Thymeleaf. Everything was going smoothly, until I encountered an issue when trying to send JSON data. I noticed that the double quote (" ...

Angular encountered an issue while attempting to access the property 'results' of an undefined value

I've got the code functioning perfectly, but for some reason I'm not getting any errors in the console log. It seems like I can't access results from an indefinite property. Any ideas on what could be causing this issue? I'm trying to m ...

When a label is clicked, the ng-change event is not triggered on the corresponding radio button

I developed a custom directive that allows you to select a radio button by focusing on its label and pressing the spacebar. However, although the radio button is checked, the ng-change function action() does not get triggered. Below is the HTML code snipp ...

Unexpected request causes a dilemma during the karma test for an Angular directive

Let's discuss a straightforward directive: 'use strict'; angular .module('app') .directive('ngEmailMask', ngEmailMask); function ngEmailMask() { var directive = { replace: true, restrict: 'EA', ...

Verify that the text entered in the form is accurate, and if it meets the required criteria, proceed to the next

Is it possible to achieve this without using JavaScript? If not, I'd like to find the simplest solution. I have a form that functions similar to a password entry field, and I would like to redirect users to a certain page if they type in a specific p ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

Using Jquery to Switch Pages

Recently, I've been experimenting with using hashes to create animated transitions between pages. Interestingly, the first page that loads (the home page) fades in and out seamlessly. However, when I attempt to navigate to another page, specifically t ...

What is the best method to compare dates in JavaScript/JQuery to determine if one comes before the other?

I am completely new to JavaScript development and I need to accomplish the task below: I have 2 input tags containing 2 strings representing dates in the format 01/12/2014 (DAY/MONTH/YEAR). These input tags are used to search for objects with a date field ...

Can angular and grunt support multiple run blocks simultaneously?

Currently, I am configuring $httpBackend to simulate fake API routes while our team of API developers is building them out. However, I am facing an issue where I have to place all the $httpBackend configurations within my run block. This leads to a situa ...

What are the steps to integrate openjphjs with next.js?

I am working on a project with Next.js and need to utilize openjphjs for decoding HTJ2K pixel data. In order to incorporate openjphjs, I have included both openjphjs.js and openjphjs.wasm in a specific folder within the project structure. To address an e ...

Tips for stopping PHP echo from cutting off a JS string?

I encountered an issue with my code: <!DOCTYPE html> <html> <head> <title>Sign up page</title> <meta charset="UTF-8"/> </head> <body> <h1>Sign up page</h ...

Encountering issues when attempting to establish the initial date of a react DatePicker based on the user's timezone

I am currently working on a React project and facing an issue with setting the default date of a DatePicker component to the user's timezone received from an API. Despite several attempts, I keep encountering an error whenever I try to inject the date ...

How can I detect if a control value has been changed in a FormGroup within Angular 2? Are there any specific properties to look

I am working with a FormGroup that contains 15 editable items, including textboxes and dropdowns. I am looking to identify whether the user has made any edits to these items. Is there a specific property or method I can use to check if the value of any i ...

Is it possible to display a title tooltip only when the CSS ellipsis feature is active in a React component?

Issue: I am trying to find a neat solution to display a title tooltip on items that have a CSS ellipsis applied, within a React component. Approaches Attempted: I created a ref, but it only exists after componentDidUpdate. Therefore, I force an update w ...

Putting off the jQuery UI autocomplete focus event

Currently, I am utilizing an autocomplete feature from version 1.8.23 of the jQuery UI library. Here is a snippet of my code: $(this).autocomplete({ autoFocus: true, minLength: 2, delay: 100, source: function(request, response) ...

Error: TweenLite has not been recognized

/justincavery/pen/mPJadb - this is a link to CodePen After copying the code from CodePen and running it, I encountered an error: "Uncaught ReferenceError: TweenLite is not defined". The image only draws once and there is no animation unless I press "F5 ...

jquery method to make entire navigation bar clickable

I have a single menu bar. I recently discovered an interesting way to make the entire menu bar area clickable using jQuery. Design code snippet: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MenuControl.ascx.cs" Inherits="MenuControl"%> ...

Storage in Ionic and variable management

Hello, I'm struggling to assign the returned value from a promise to an external variable. Despite several attempts, I have not been successful. export class TestPage { test:any; constructor(private storage: Storage) { storage.get('t ...