我在应用脚本中具有以下内容:
function getQAs() {
return [
{ "Do you have any pictures ?|1 ": {"yes":2,"no":3 } },
{ "Do you have any pictures ?|2 ": {"yes":2,"no":3 } },
{ "Do you have any pictures?|3 ": {"yes":2,"no":3 } },
]
}
我正在尝试构建一个函数,该函数将通过The objects的键搜索数字。我正在测试数字1。运行时:
function testQA() {
var qa = getQAs();
var matches = qa.keys().filter(function(row) { //ONLY CHECKED ROWS.
Logger.log(row)
return row.indexOf('1') == true;
});
Logger.log(matches);
}
我知道
JS:TypeError:在object中找不到功能键。我在做什么错了?
答案 0 :(得分:1)
您需要使用for...in
循环来获取对象的键。我设计了一个遍历键的简单循环,以确定键中是否存在该值,然后推出一个过滤后的数组
function testQA() {
var qa = getQAs();
function getRow(row_identifier) {
var filtered = [];
qa.forEach(function(v) {
for(var k in v) {
if(k.indexOf(row_identifier) > 0) filtered.push(v);
}
});
return filtered;
}
return getRow(row_identifier);
}
function getQAs() {
return [
{
"Do you have any pictures ?|1 ": {
"yes": 2,
"no": 3
}
},
{
"Do you have any pictures ?|2 ": {
"yes": 2,
"no": 3
}
},
{
"Do you have any pictures?|3 ": {
"yes": 2,
"no": 3
}
},
]
}
function testQA() {
var qa = getQAs();
function getRow(row_identifier) {
var filtered = [];
qa.forEach(function(v) {
for(var k in v) {
if(k.indexOf(row_identifier) > 0) filtered.push(v);
}
});
return filtered;
}
console.log(getRow(1));
console.log(getRow(2))
console.log(getRow(3))
}
testQA();
答案 1 :(得分:1)
我对物体不是很好,所以我觉得玩这个东西并看看我能学到什么会很有趣。我没想到会选择答案,我只是认为这对像我这样经验不足的程序员可能很有价值。
function getQAs() {
var qa=[{"Do you have any picture?|1":{yes:"2",no:"3"}},{"Do you have any picture?|2":{yes:"4",no:"5"}},{"Do you have any picture?|3":{yes:"8",no:"9"}}];
return qa;
}
function testQA(row) {
var row=row || 3;
var qa = getQAs();
Logger.log(qa);
var qA=[];
for(var i=0;i<qa.length;i++) {
qA.push(Object.keys(qa[i]));
}
Logger.log(qA);
for(var i=0;i<qA.length;i++) {
if(qA[i].toString().indexOf(row)>-1){
var rv=JSON.stringify(qa[i]);
var t1=qA[i];
var t2=qa[i];
var yeses=t2[t1].yes;
var nos=t2[t1].no;
var t3={yes:yeses,no:nos};
return t3;
break;
}
}
}