I have what is essentially a questionnaire in the form of a SQL model.
User answers the questions, creates the item. With the item loaded, how can I loop through the values? I'm new to JS and GAM, but I've tried the below and can only seem to get the name of the fields, not its value.
function generateScore(){
ds = app.datasources.Checklist.item;
for (var x in ds){
if (ds.x === 'Safe'){
console.log("Passed");
} else {
console.log("Failed");
}
}
}
Output will be 'Fail' as 'ds.x' is only returning the name of the field and not its value.
It's probably really simple, but can somebody guide me in the right direction? Thanks
Short answer: In your function change ds.x to ds[x]:
function generateScore(){
ds = app.datasources.Checklist.item;
for (var x in ds){
if (ds[x] === 'Safe'){
console.log("Passed");
} else {
console.log("Failed");
}
}
}
TL;DR
There are Other ways of looping through the values of an object. Let's assume the following object:
const obj = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
};
You can use the Object.keys syntax.
JS ES6 answer:
Object.keys(obj).map(key => obj[key]) // returns an array of values --> ["value1", "value2", "value3"]
Object.keys(obj).map(key => {
console.log(obj[key])
})
// logs all values one by one --> "value1" "value2" "value3"
JS ES5 answer:
Object.keys(obj).map(function(key) {
console.log(obj[key])
});