cappuccinoobjective-j

how to iterate literal dictionary in cappucino objective-j


Please an help to iterate literal dictionary on cappuccino environment.Thanks

var userDict = @{@"name": @"Jack",@"secondName": @"Buck",@"name":  @"Jacob",@"secondName": @"Smith"};

for (var righe in userDict){

console.log(righe.name + righe.secondName);
}
output NaN

Solution

  • I'd probably do something like this:

    for (var key in [userDict allKeys])
    {
        console.log(key, userDict[key]);
    }
    

    But your dictionary looks wrong; this:

    @{
        @"name":         @"Jack",
        @"secondName":   @"Buck",
        @"name":         @"Jacob",
        @"secondName":   @"Smith"
    };
    

    Will overwrite the name and secondName indices and result in:

    @{
        @"name":         @"Jacob",
        @"secondName":   @"Smith"
    };
    

    You probably wanted a CPArray of CPDictionary:

    var users = [
        @{
            @"name":         @"Jacob",
            @"secondName":   @"Smith"
        },
        @{
            @"name":         @"Jacob",
            @"secondName":   @"Smith"
        }
    ];
    

    Then if you loop over users; you get one user dictionary for each step in the loop, and you can address its ' indices (properties). Since both CPArray and CPDictionary are tollfree-bridged to their native javascript counterparts, you can still do this:

    for (var ix = 0; ix < users.length; ix ++)
    {
       var user = users[ix];
       console.log(user.name, user.secondName);
    }
    

    Hope this helps.