1

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.

  • 2
    `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.` you did it wrong ... show what you've done – Jaromanda X May 10 '18 at 08:29
  • I passed the javascript object as it is to the functions, but each one is giving me the same output. – Segmentation Fault May 10 '18 at 08:51
  • right ... that sentence doesn't look like javascript, sounds like a vague description of something ... StackOverflow isn't a free code-writing service, and expects you to [try to solve your own problem first](http://meta.stackoverflow.com/questions/261592). Please update your question to show what you have already tried, showing the specific problem you are facing in a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve). – Jaromanda X May 10 '18 at 08:54

2 Answers2

4

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));
Eddie
  • 26,593
  • 6
  • 36
  • 58
2

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);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59