迭代嵌套的Javascript对象

时间:2018-05-10 08:25:54

标签: javascript

我有一个像

这样的javascript对象
{
"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}
}

我想迭代所有外键,例如DateOpen Price来创建表头,然后遍历内部元素来创建行。我已经尝试了this answer,但它的作用是遍历每个值,即使Date被迭代为Dat,{ {1}}。是否有可能或者是否有其他方法可以从javascript对象创建表。

2 个答案:

答案 0 :(得分:4)

您可以使用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));

答案 1 :(得分:1)

您可以尝试以下



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