Chartjs-Extract data from an array of Object

0👍

First of all you need to create an array for each property you want to plot; i.e.:

var fsp = [],
    msg = [],
    sgw = [];

Then you can loop over your dataset and put the data in each array:

yourArray.forEach(function(obj){
    //obj takes the value of each object in the database
    fsp.push(obj.fsp);
    msg.push(obj.msg);
    sgw.push(obj.sgw);
})

or, if you are more familiar with for loop

for(var obj of yourArray){
    fsp.push(obj.fsp);
    msg.push(obj.msg);
    sgw.push(obj.sgw);
}

Finally you can create an array as you pointed in your example

var result = [];

result.push(fsp, msg, sgw);

And the result will be

[
    [89, 59, 43, 60, 81, 34, 28, 58, 75, 41],
    [77, 91, 4, 56, 6, 1, 42, 82, 97, 18],
    [24, 34, 4, 13, 75, 34, 14, 41, 20, 38]
]

For more informations take a look at Array.forEach(), Array.push() and for...of documentations

EDIT

As you pointed in your comment, you can generate arrays dynamically creating an object like var arrays = {};. Then in forEach(), or if for...of, you need to loop over objects with a for...in loop. The variable you declare in loop’s head takes the value of index, numeric for Arrays, literal for Objects. You have to do something like:

yourArray.forEach(function(obj){
    for(let index in obj){
        if(!arrays[index]) // check if property has already been set and initialized
            arrays[index] = []; // if not, it's initialized

        arrays[index].push(obj[index]) // push the value into the array
    }
})

Note that Object has been treated as Array because you access its properties with a variable filled at runtime.

The result will be:

arrays = {
    fsp: [89, 59, 43, 60, 81, 34, 28, 58, 75, 41],
    msg: [77, 91, 4, 56, 6, 1, 42, 82, 97, 18],
    sgw: [24, 34, 4, 13, 75, 34, 14, 41, 20, 38]
}

To obtain only arrays use Object.values().

If you cannot imagine how this works, I suggest you to make some examples in Chrome Developer Tools’ console, or in Node’s console, or wherever you can have a realtime feedback, putting in the middle of code some console.log() of variables

1👍

You can do it like this:

let array1 = [
  {
    param1: 10,
    param2: 20
  },
  {
    param1: 30,
    param2: 40
  }
]

let array2 = array1.map(item => Object.values(item));

console.log(array2); // prints [[10, 20], [30, 40]]

Leave a comment