Reputation: 13
I am trying to iterate over an dictionary that has values in form of array those values I want to put in a dictionary I am confused as to what should I do to obtain this
Here is the data that I want to iterate over :
{
t: ["20181019,20181022,...."],
o: ["180.34,189.45,..."],
h: ["180.99,181.40,..."],
l: ["178.57,177.56,...."],
c: ["179.85 ,178.75,...."]
}
Here is what the end product should look like :
[
{ time: '20181019', open: 180.34, high: 180.99, low: 178.57, close: 179.85 },
{ time: '20181022', open: 180.82, high: 181.40, low: 177.56, close: 178.75 },
{ time: '20190509', open: 193.31, high: 195.08, low: 191.59, close: 194.58 },
]
Upvotes: 0
Views: 993
Reputation: 277
Try below code.
var data = {
t: ["20181019,20181022"],
o: ["180.34,189.45"],
h: ["180.99,181.40"],
l: ["178.57,177.56"],
c: ["179.85 ,178.75"]
}
var res = [];
const open = data.o.toString().split(",");
const high = data.h.toString().split(",");
const low = data.l.toString().split(",");
const close = data.c.toString().split(",");
data.t.toString().split(",").forEach((item, index) => {
res.push({
time : item,
open : open[index],
high: high[index],
low: low[index],
close: close[index]
});
})
console.log(res);
Upvotes: 0
Reputation: 444
Here is the quick solution:
const data = {
t: ['20181019,20181022,....'],
o: ['180.34,189.45,...'],
h: ['180.99,181.40,...'],
l: ['178.57,177.56,....'],
c: ['179.85 ,178.75,....'],
};
let prepared = {};
Object.keys(data).map((key) => {
prepared[key] = data[key][0].split(',');
});
const res = prepared.t.map((tVal, index) => {
return {
time: tVal,
open: prepared.o[index],
high: prepared.h[index],
low: prepared.l[index],
close: prepared.c[index],
};
});
console.log(res);
Upvotes: 1
Reputation: 25408
You can easily achieve the result using Object.keys, reduce
const obj = {
t: ["20181019,20181022"],
o: ["180.34,189.45"],
h: ["180.99,181.40"],
l: ["178.57,177.56"],
c: ["179.85 ,178.75"],
};
const dict = { t: "time", o: "open", h: "high", l: "low", c: "close" };
const tempObj = Object.keys(obj).forEach((k) => (obj[k] = obj[k][0].split(",")));
const result = Array.from({ length: obj.t.length }, (_, i) => {
return Object.entries(obj).reduce((acc, [k, v]) => {
acc[dict[k]] = k === "t" ? v[i] : +v[i];
return acc;
}, {});
});
console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1