http://coldfusion.com logo
#cfml-general
Title
# cfml-general
s

Simone

03/04/2022, 1:02 PM
trying to find if the key views exists, only do some work, what is wrong i am doing
Copy code
for (d in posts) {
            for (key in d) {
               
               structkeyexists(key,'views');
               dump(key);
            }
        }
t

Tim

03/04/2022, 1:08 PM
Without the output you're actually getting, it's hard to tell anything. Is posts empty? Is d empty? Both of those would result in no output. Or are you getting an error? Is posts not a struct, an array, or a list? Same question for d. Is key not a struct?
a

Adam Cameron

03/04/2022, 2:03 PM
@Simone we've been through this before. Don't ask "what am I doing wrong?", tell us what the code is doing, what your expectations are (you did that bit... kinda), and how the code's behaviour is differing from your expectations. And a summary of what troubleshooting you have already done.
Questions for you (which are things you should have already done): • what parameters does
structKeyExists
take? • And what are you giving it? • Does that seem right? • What are you expecting the statement
structkeyexists(key,'views')
, by itself, to do?
s

Simone

03/04/2022, 2:42 PM
if(structkeyexists(d,'views')) { this will work
t

Tim

03/04/2022, 3:30 PM
I'm taking that to mean that
d
is a struct and
d
has a
views
key. I'm just going to guess at your data structure here, because you still haven't told us... And that posts is an array of structs, like so:
Copy code
var posts = [
    {
        subject: "Post 1",
        content: "This is the first post",
        views: 14
    },
    {
        subject: "Post 2",
        content: "Post 1 is stupid. I disagree.",
        views: 6
    }
];
Then, your code would be
Copy code
for (d in posts) {
    for (key in d) {
        structkeyexists(key, "views");
        dump(key);
    }
}
And processing it would look like this:
Copy code
1. posts has 2 items, so it enters the loop.
2. d = the first struct (post 1)
3. d has keys, so it enters the second loop.
4. key = "subject"
5. structkeyexists("subject", "views") throws an error because "subject" is not a struct. It's a string.