我有以下数组,我想循环遍历它并将键值推送到另一个声明的数组。然后,循环遍历数组并将键的字段和值推送到另一个数组。
timeframe = [];
timeframeValueKeyUSD = [];
timeframeValueKeyCAD = [];
array = [
{
"2012-05-01":{
"USD": 1.322891,
"AUD": 1.278047,
"CAD": 1.302303
},
"2012-05-02": {
"USD": 1.315066,
"AUD": 1.274202,
"CAD": 1.299083
},
"2012-05-03": {
"USD": 1.314491,
"AUD": 1.280135,
"CAD": 1.296868
}
}
]
我想得到这样的数组:
timeframe = ['2012-05-01', '2012-05-02', '2012-05-03'];
timeframeValueKeyUSD = [1.315066, 1.315066, 1.314491];
timeframeValueKeyCAD = [1.302303, 1.299083, 1.296868];
最佳答案
您可以先获取日期,然后根据日期映射值。
function getKeys(o) {
return Object.keys(o);
}
function getValueBy(object, groups, key) {
return groups.map(k => object[k][key]);
}
var array = [{ "2012-05-01":{ USD: 1.322891, AUD: 1.278047, CAD: 1.302303 }, "2012-05-02": { USD: 1.315066, AUD: 1.274202, CAD: 1.299083 }, "2012-05-03": { USD: 1.314491, AUD: 1.280135, CAD: 1.296868 } }],
timeframe = getKeys(array[0]);
timeframeValueKeyUSD = getValueBy(array[0], timeframe, 'USD'),
timeframeValueKeyCAD = getValueBy(array[0], timeframe, 'CAD');
console.log(timeframe);
console.log(timeframeValueKeyUSD);
console.log(timeframeValueKeyCAD);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何循环遍历对象数组,将键推送到另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50830561/