我有一个看起来像这样的(多个国家)的数据
[
{country:"Country1", GDP : 12345, GDPgrowth : {year1:123, year2:234, year3:345}},
{country:"Country2", GDP : 12345, GDPgrowth : {year1:123, year2:234, year3:345}}
]
我能够通过使用forEach
和循环在“行”来访问每个国家的数据。
然而,我无法弄清楚如何GDPgrowth
中访问单个值。我试图做一个嵌套forEach
,但它抛出一个错误它不是一个功能,我想这是因为GDPgrowth
内的数据是不是数组。我也尝试了通用的for循环的做法,但也似乎没有达到我所期待的。
什么是进入这些值(理想情况下,无需通过名称year1
,year2
,year3
每次选择)推荐的方法?
一个解决方案是使用Object.values()获得与对象值的数组,你可以使用forEach()
遍历他们。
const input = [
{country: "Country1", GDP: 12345, GDPgrowth: {year1:123, year2:234, year3:345}},
{country:"Country2", GDP : 12345, GDPgrowth : {year1:123, year2:234, year3:345}}
];
input.forEach(x =>
{
console.log("country: " + x.country);
Object.values(x.GDPgrowth).forEach(y => console.log("year: " + y))
});
另外,我建议阅读有关Object.keys()和Object.entries()了。