Chartjs-How to get hundreds of JS object properties into arrays to use as chart.js axes/data

0👍

Okay listen up you stinkin’ noob. You’re 99% of the way there.

First, we rephrase your problem into a generalized question to pacify the angry spirits that haunt stackoverflow:

I have an array of cryptoprices. How do I turn it into data that chart.js
can use?

This is a ‘do my homework’ question, which will make stackoverflow throw a syntax error and possibly angry downvotes.

We must therefore break it down, find the crux of the matter and tidy it up.

  • What does chart.js accept as data?
    • In chart.js‘s webpage you can find its docs, which seem pretty well-written. Since you want to plot price vs. time, you need points, a.k.a. something like [{x:<high price>, y:<time>}].
  • What kind of data do you have?
    • According to your question & photo you have something like: [{high: 1, time: 2, ... /*etc*/}]

Now you can ask something like

How can I convert an array of objects of one type into an array of objects of another type?

I have to draw cryptoprices with some library. How can I elegantly transform an array of {high: 1, time: 2, ... /*etc*/} into an array of {x:<high price>, y:<time>}?

Three things can happen. One, you find someone else asked this same question already which you wouldn’t have known without first taking this step. Two, by trying to find a better way to ask the question, you found the answer yourself (which you almost did, good job btw). Three, you still need to ask it anyway, but now your question is pretty and you will attract all the stackoverflow fairies who will now compete to answer your worthy question, even thought it’s same question as before.

Second, we transform an array of objects of one type into an array of objects of another type using the map function

var cryptoprices = [
  {high:1, time:1, fields:"that", you:"don't", care:"about"},
  {high:9, time:2, otherfields:"that", arein:"theway"}
];

//map is a function that all arrays have.
//It calls a function on each array element, and returns an array with the results of that function.
//So you only need to focus on how you would transform a single cryptoprice into a single point of data:
function transform(cryptoprice) {
  //A single point should be an object that contains only the fields x and y.
  //Since you are interested in the price and time fields only...
  let point = {
    x: cryptoprice.time,
    y: cryptoprice.high
  }
  return point;
}

var points = cryptoprices.map(transform)
console.log(points);
// expected output: Array [Object { x: 1, y: 1 }, Object { x: 2, y: 9 }]

And finally, the short, elegant version:

cryptoprices.map(c => ({x:c.time, y:c.high}))

😀

Leave a comment