[Chartjs]-How to push array multidimensional in javascript

0👍

Your desired dataset look like an array of the objects, where every data within the curly braces is object.
So if you want to put multidimensional array in JS, create each object in a variable, add data to that and then push that to the array. Like

let arr = [];
let obj1 = {}; //add data to this object
arr.push(obj1);
let obj2 = {}; //add data to this object
arr.push(obj2);
.
.
.
let objn = {}; //add data to this object
arr.push(objn)

0👍

First you need to give the definition for your input first. The result you wrote is just a Array of Object. The multidimensional array should like this one:

const multidimensionalArray = [
  [1,2,3,4],
  [12,13,15,16],
  [17,2,31,]
]

For you question I assume you receive data from backend :

const responseData = [{data1, data2, data3, data4}]

const result = responseData.map(item => {
   /// Do some manipulate data here
   const stypingObj = item.type ? styling1 : styling2 
   const valueArray = item.valueData  // You can manipulate value also
   return chartData = { ...item. data: valueArray, ...stylingObj }
})

Then it return your expected result.

0👍

No worries, this architecture is a bit messy, always hard to write and read.

You should use something like:

var d = {
  datasets: [
    {
      label: 'Manajemen Informatika',
      data: [100, 105, 203, 160, 200],
      backgroundColor: 'rgba(189, 99, 132, 0.2)',
      borderColor: 'rgba(189, 99, 132, 1)',
      borderWidth: 1
    }
  ]
}


d.datasets.push(
  {
    label: 'Sistem Informasi',
    data: [90, 120, 225, 185, 200],
    backgroundColor: 'rgba(72, 189, 122, 0.2)',
    borderColor: 'rgba(72, 189, 122, 1)',
    borderWidth: 1
  }
)

// Read a particular value
console.log(d.datasets[1].label)

// Whole object
console.log(d)

We are not supposed to write an object by hand ourself, but chart.js is made like that, forcing every configuration as such nested in objects, and it become worst using plugins you have to pass functions there as well, this makes messy scripts.

Side note, would recommend to avoid using chart.js altogether, for different reasons.

0👍

Please try this code, To How to push array multidimensional in javascript

var PushToArray = { };
PushToArray.productID = productID;
PushToArray.itemColorTitle = itemProductTitle;
PushToArray.itemColorPath = itemProduct;
cookie_value_add.push(PushToArray);

I hope this code will be useful to you.

Thank you.

Leave a comment