gpt4 book ai didi

javascript - 当您不知道 Google Apps 脚本中的名称时,JSON/JS 对象访问 key

转载 作者:行者123 更新时间:2023-11-30 10:22:15 25 4
gpt4 key购买 nike

我正在处理来自 Google 应用程序脚本中 Webtrends API 的响应,我有一个如下所示的 JSON/JS 对象:

"data": [
{
"period": "Month",
"start_date": "2013-12",
"end_date": "2013-12",
"attributes": {},
"measures": {
"Visits": 500
},
"SubRows": [
{
"facebook.com": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"google.co.uk": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"newsnow.co.uk": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"No Referrer": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
},
"t.co": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
}
}
]
}
]

我需要访问的是名称,例如 facebook.com 等...以及每个子行的访问编号。

我能得到访问编号,但我不知道如何得到名字。请注意,名称会不断变化,因为不同的网站每天发送的流量不同。

我获得访问次数时的代码部分:

for(i in dObj){
var data = dObj[i].SubRows;
var sd = dObj[i].start_date;
var ed = dObj[i].end_date;

if(sd == ed){
var timep = ""+ sd;
}
else{
var timep = ""+ sd + "-" + ed;
}

var subRows = data[0];

Logger.log(subRows);

for(i in subRows){

var row = subRows[i];
var rmeasures = row.measures;
var rvis = rmeasures.Visits;

values = [timep,"",rvis]; //Blank string for where the name of the site would go
}

}

我试过以下链接,但似乎都没有答案:

Getting JavaScript object key list How to access object using dynamic key? How to access key itself using javascript How do I access properties of a javascript object if I don't know the names?

我只是使用 vanilla google apps 脚本,因为我对 Jquery 等没有任何经验......

如有任何帮助,我们将不胜感激!

最佳答案

我通常使用如下所示的小辅助函数:

var keyVal = function(o) {
var key = Object.keys(o)[0];
return {"key": key, "val":o[key]};
} ;

这会将具有可变键的对象映射到键/值对象 {key:...., val:{}},这通常很方便使用。

describe.only ("stack overflow answer", function(){

it ("is should create a key/value pair" , function(){

var res = keyVal( {
"facebook.com": {
"attributes": {},
"measures": {
"Visits": 100
},
"SubRows": null
}});
res.key.should.equal('facebook.com');
res.val.attributes.should.deep.equal({});
});

关于javascript - 当您不知道 Google Apps 脚本中的名称时,JSON/JS 对象访问 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21076431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com