Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting array of objects into array for Google Charts

I have an array of objects:

    [
      {
      SalePrice:"18000",
      TotalValue:"22500"
      ratio:1.25
      }
      {
      SalePrice:"128000",
      TotalValue:"212500"
      ratio:1.05
      }
    ]

and I want to form it into an array. like:

[
        [18000,  22500, 1.25],
        [128000,  212500, 1.05]
]

Using JS (ES6 is ok). I have tried using somelike like:

let array = data.map(({SalePrice, TotalValue, ratio}) => SalePrice, TotalValue, ratio).filter(s => s, t = >t, r => r);

but that doesn't work could anyone enlighten me please?

like image 462
5pence Avatar asked Oct 02 '18 11:10

5pence


People also ask

How do you transform an array into an object?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied! const arr = ['zero', 'one', 'two']; const obj4 = arr.


2 Answers

Maybe something like the following:

const data = [{SalePrice:"18000",TotalValue:"22500",ratio:1.25},{SalePrice: "128000",TotalValue:"212500",ratio:1.05}]
const mappedToArray = data.map(d => Array.from(Object.values(d)))
//[["18000", "22500", 1.25],["128000", "212500", 1.05]]

The advantage of this approach is not having to rely on hardcoded keys to access to properties in your object which the other answer does need. Which could also be a disadvantage in it's own if that includes properties Google Charts does not need.

like image 71
nbokmans Avatar answered Oct 16 '22 21:10

nbokmans


let objectArray = ...;
let container = [];

objectArray.forEach(e => container.push([e.SalePrice, e.TotalValue, e.ratio]));
like image 45
Adam Avatar answered Oct 16 '22 20:10

Adam