我正在嘗試迭代一個有陣列形式的值的字典,我想把這些值放在一個字典里,我很困惑,我應該怎么做才能獲得這個值
下面是我想迭代的資料。
這是我想迭代的資料:
{
t: ["20181019,20181022,...."],
o: ["180.34,189.45,..."],
h: ["180.99,181.40,..."],
l: ["178.57,177.56,...."],
c: ["179.85 ,178.75,...."]
}
這就是最終產品的樣子:
[
{ time: '20181019', open: 180.34, high: 180.99, low: 178.57, close: 179.85 },
{ 時間: '20181022', open: 180.82, high: 181.40, low: 177.56, close: 178.75 },
{ 時間: '20190509', open: 193.31, high: 195.08, low: 191.59, close: 194.58 },
]
uj5u.com熱心網友回復:
你可以使用Object.key, 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: "高", l: "低", c: "close" }。
const tempObj = Object.keys(obj)。 forEach((k) => (obj[k] = obj[k][0] 。 split(",") )。
const result = Array.from({ length: obj. t.length }, (_, i) =>/span> {
return Object.entries(obj)。 reduce((acc, [k, v]/span>) => {
acc[dict[k]] = k === "t" ? v[i] : v[i] 。
return acc;
}, {});
});
console.log(result);
/* This is not a part of answer. 它只是為了給輸出填充高度。所以請忽略它 */
.as-console-wrapper { max-height: 100% ! important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
下面是快速的解決方案:
。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) => /span> {
prepared[key] = data[key][0].split(', ')。
});
const res = prepared.t.map((tVal, index) => /span> {
return {
time: tVal,
open: prepared.o[index] 。
high: prepared.h[index],
低: prepared.l[index],
close: prepared.c[index]。
};
});
console.log(res);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
試試下面的代碼。
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);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/327333.html
標籤:
