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?
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.
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.
let objectArray = ...;
let container = [];
objectArray.forEach(e => container.push([e.SalePrice, e.TotalValue, e.ratio]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With