我需要帮助。我对如何以正确的方式获取对象数据感到困惑。当console.log(response.data.data(我的数据如下所示:
Object {
"2014": Object {
"1": "3.385",
"10": "-0.191",
"11": "0.383",
"12": "0.191",
"2": "3.023",
"3": "3.667",
"4": "3.774",
"5": "-2.045",
"6": "2.088",
"7": "5.455",
"8": "-3.448",
"9": "16.741",
},
"2015": Object {
"1": "1.905",
"10": "5.092",
"11": "-4.070",
"12": "7.475",
"2": "5.421",
"3": "5.142",
"4": "-9.106",
"5": "4.824",
"6": "-4.425",
"7": "-2.963",
"8": "-1.527",
"9": "-4.845",
},
"2016": Object {
"1": "-1.504",
"10": "-1.115",
"11": "-7.891",
"12": "8.392",
"2": "2.863",
"3": "-1.299",
"4": "-1.880",
"5": "-0.383",
"6": "2.500",
"7": "8.443",
"8": "4.152",
"9": "4.319",
}
}
我无法使用console.log(response.data.data.2014(或console.log(response.data.data.object(.
我想获取年份和月份的对象数据。如何获取此对象数据?
谢谢
你可以这样做
const data = {
"2014": {
"1": "3.385",
"10": "-0.191",
"11": "0.383",
"12": "0.191",
"2": "3.023",
"3": "3.667",
"4": "3.774",
"5": "-2.045",
"6": "2.088",
"7": "5.455",
"8": "-3.448",
"9": "16.741",
},
"2015": {
"1": "1.905",
"10": "5.092",
"11": "-4.070",
"12": "7.475",
"2": "5.421",
"3": "5.142",
"4": "-9.106",
"5": "4.824",
"6": "-4.425",
"7": "-2.963",
"8": "-1.527",
"9": "-4.845",
},
"2016": {
"1": "-1.504",
"10": "-1.115",
"11": "-7.891",
"12": "8.392",
"2": "2.863",
"3": "-1.299",
"4": "-1.880",
"5": "-0.383",
"6": "2.500",
"7": "8.443",
"8": "4.152",
"9": "4.319",
}
}
for (const year in data) {
console.log(`${year}: ${data[year]}`);
for (const month in data[year]) {
console.log(`${month}: ${data[year][month]}`);
}
}
这是它的文件:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
如果我们查看您的对象,您将使用一个整数作为键。尽管您已将整数转换为字符串,但仍不能将其用作data.2014
。你必须使用data["2014"]
。
✔当您的对象看起来像这样时,数据对象的密钥名称只能作为data.key
使用:
const data = {
key: "Value"
}
或
const data = {
key2022: "Value"
}
✘但是,当您在密钥中使用integer before时,或者您使用唯一的整数来命名密钥,并且您需要使用data["key"]
:时,它将不起作用
const data = {
"1key": "Value"
}
或
const data = {
"1234": "Value"
}
✔所以,如果你想得到这个值,你必须使用这个代码,并尝试使用data["key"]
而不是data.key
作为你的对象。
const data = {
"2014": {
"1": "3.385",
"10": "-0.191",
"11": "0.383",
"12": "0.191",
"2": "3.023",
"3": "3.667",
"4": "3.774",
"5": "-2.045",
"6": "2.088",
"7": "5.455",
"8": "-3.448",
"9": "16.741",
},
"2015": {
"1": "1.905",
"10": "5.092",
"11": "-4.070",
"12": "7.475",
"2": "5.421",
"3": "5.142",
"4": "-9.106",
"5": "4.824",
"6": "-4.425",
"7": "-2.963",
"8": "-1.527",
"9": "-4.845",
},
"2016": {
"1": "-1.504",
"10": "-1.115",
"11": "-7.891",
"12": "8.392",
"2": "2.863",
"3": "-1.299",
"4": "-1.880",
"5": "-0.383",
"6": "2.500",
"7": "8.443",
"8": "4.152",
"9": "4.319",
}
}
// To access the object of specific year use data["year"]
console.log(data["2014"])
// To access the value of specific month use data["year"]["month"]
console.log(data["2014"]["2"])