[英]Iterate through nested Javascript object
我有一個像
{
"Date":{"0":"30-April-2018","1":"27-April-2018","2":"26-April-2018"},
"Open Price":{"0":15.75,"1":16.8,"2":17.5},
"High Price":{"0":15.85,"1":17.0,"2":17.5},
"Low Price":{"0":14.65,"1":15.6,"2":16.35}
}
我想遍歷所有外部鍵(如Date
, Open Price
以創建表標題,然后遍歷內部元素以創建行。 我已經嘗試過這個答案 ,但是它的作用是遍歷每個值,即使Date
迭代為D
, a
, t
, e
。 有可能還是有其他方法可以從javascript對象制作表格。
您可以使用Object.keys
來獲取密鑰。 這將返回所有標頭。
您可以使用Object.values
來獲取所有值,使用reduce
來匯總數據。
let obj = {"Date":{"0":"30-April-2018","1":"27-April-2018","2":"26-April-2018"},"Open Price":{"0":15.75,"1":16.8,"2":17.5},"High Price":{"0":15.85,"1":17.0,"2":17.5},"Low Price":{"0":14.65,"1":15.6,"2":16.35}} let headers = Object.keys(obj); let content = Object.values(Object.values(obj).reduce((c, v) => { Object.entries(v).map(([i, o]) => { c[i] = c[i] || []; c[i].push(o); }); return c; }, {})); console.log(headers); //Every array element of content will a row on the table //Loop content as content.forEach(o=>console.log(o));
您可以嘗試關注
var obj = { "Date":{"0":"30-April-2018","1":"27-April-2018","2":"26-April-2018"}, "Open Price":{"0":15.75,"1":16.8,"2":17.5}, "High Price":{"0":15.85,"1":17.0,"2":17.5}, "Low Price":{"0":14.65,"1":15.6,"2":16.35} }; var headers = Object.keys(obj); // get the header row var rows = []; // this will be collection of data // get the values and iterate over them Object.values(obj).forEach((item) => { // iterate over every value in the object and push it in array Object.values(item).forEach((val, index) => { rows[index] = rows[index] || []; rows[index].push(val); }); }); console.log(headers); console.log(rows);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.