Reputation: 75
I am trying to convert that kind of array to an object while formating the date to be able to use it with a chart.
Here is a snippet of what I did so far
arr=[1524314460000,0.067872,0.067876,0.067876,0.06785,0.41500986]
var obj = {...arr}
const newKeys = {0: new Date("time"), 1: "open" , 2:"low",3:"high",4:"close",5:"volume" };
function renameKeys(obj, newKeys) {
const keyValues = Object.keys(obj).map(key => {
const newKey = newKeys[key] || key;
return { [newKey]: obj[key] };
});
return Object.assign({}, ...keyValues);
}
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj)
As you can see I able to convert it to an object but I cant use new Date()
to convert the time , Any idea on how to approach the task as you can see I am getting invalid date
.
Thank you
Upvotes: 1
Views: 47
Reputation: 22866
Seems like just using the array indexes would be enough:
var arr = [1524314460000, 0.067872, 0.067876, 0.067876, 0.06785, 0.41500986]
var obj = {
time: new Date(arr[0]),
open: arr[1],
low: arr[2],
high: arr[3],
close: arr[4],
volume: arr[5]
}
console.log(obj)
Upvotes: 1
Reputation: 10262
You can also directly use your Array
to convert into object using reduce()
or map
to get the required result.
DEMO
const arr = [1524314460000, 0.067872, 0.067876, 0.067876, 0.06785, 0.41500986],
newKeys = {
0: 'time',
1: "open",
2: "low",
3: "high",
4: "close",
5: "volume"
};
function renameKeys(arr, newKeys) {
return arr.reduce((r,v,i)=>{
i = newKeys[i];
r[i]= i == 'time'? new Date(v):v;
return r;
},{});
}
console.log(renameKeys(arr, newKeys))
.as-console-wrapper { max-height: 100% !important; top: 0;}
Upvotes: 1
Reputation: 30739
Remove new Date()
from newKeys
as you need date in the value of time
key. Simply add a condition in the map
that will check if the property is time
or not. If it is, change it to date with new Date(obj[key])
arr=[1524314460000,0.067872,0.067876,0.067876,0.06785,0.41500986]
var obj = {...arr}
const newKeys = {0: "time", 1: "open" , 2:"low",3:"high",4:"close",5:"volume" };
function renameKeys(obj, newKeys) {
const keyValues = Object.keys(obj).map(key => {
if(newKeys[key] === 'time'){
obj[key] = new Date(obj[key]);
}
const newKey = newKeys[key] || key;
return { [newKey]: obj[key] };
});
return Object.assign({}, ...keyValues);
}
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj)
Upvotes: 1