I'm looking to transform this...
[
[ 'market', 'type', 'timeframe', 'proximal', 'distal', 'risk', 'tradeable' ], // object keys
[ 'AD', 'DZ', 'daily', '0.6375', '0.6283', '$920.00', 'FALSE' ] // key values
]
into this...
[
{
market: 'AD',
type : 'DZ',
timeframe: 'daily',
proximal: '0.6375',
distal: '0.6283',
risk: '$920.00',
tradeable: 'FALSE'
}
]
So far, here's what I have...
// each element of the array (I call a 'zone')
data.forEach(z => {
// each element inside the 'zone'
z.forEach(e => {
// headings to object keys, where k = key and v = value
const obj = headings.reduce((k,v) => (k[v]="",k),{})
console.log(obj)
})
})
console.log(obj) outputs this to the console:
Object {
distal: "",
market: "",
proximal: "",
risk: "",
timeframe: "",
tradeable: "",
type: ""
}
I just cant figure out how to get the values into those key pairs, PLEASE HELP!!
Thanks in advance,
Sam
Use a reduce, a reduce runs a function on every element of an array and returns an accumulator each iteration. In this case the starting accumulator is the empty object {}, and on each iteration we add the key to the accumulator with the value coming from the current index in the other array.
const data = [
[ 'Market', 'Type', 'Timeframe', 'Proximal', 'Distal', 'Risk', 'Tradeable' ],
[ 'AD', 'DZ', 'daily', '0.6375', '0.6283', '$920.00', 'FALSE' ],
[ 'EC', 'SZ', 'daily', '1.13475', '1.13895', '$525.00', 'FALSE' ],
[ 'DXY', 'DZ', '60 min', '96.85', '96.76', '', 'FALSE' ]
];
const match = (keys, values) => keys.reduce((result, key, index) => {
result[key] = values[index];
return result;
}, {});
const matchAll = data => data.reduce((results, current, index) => {
if (index) {
results.push(match(data[0], data[index]));
}
return results;
}, []);
console.log(matchAll(data));
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