简体   繁体   中英

Iterate through nested Javascript object

I have a javascript object like

{
"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}
}

I want to iterate through all the outer keys such as Date , Open Price to create table headers and then iterate through inner elements to create rows. I have already tried this answer , but what it does is iterate through each and every value, even Date is iterated as D , a , t , e . Is it possible or is there any other way I can make a table from javascript object.

You can use Object.keys to get the keys. This will return all headers.

You can use Object.values to get all the values, use reduce to summarise your data.

 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)); 

You can try following

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM