Search code examples
arraysjsonios7

how do i do the same thing in iOS from javascript


function findId(data, idToLookFor) {
    var categoryArray = data.category;
    for (var i = 0; i < categoryArray.length; i++) {
        if (categoryArray[i].id == idToLookFor) {
            return(categoryArray[i].product);
        }
    }
}

var item = findId(data, 1);

Solution

  • Why don't you use a library for this, for example: http://www.jsonmodel.com/

    Anyways, here you are the version of your code in ObjectiveC:

    +(id)findId:(NSMutableArray *)data idToLookFor:(NSNumber *)idToLookFor
    {
        NSMutableArray *categoryArray = [data valueForKey:@"category"];
        for (int i = 0; i < categoryArray.count; i++) {
            if ([[categoryArray[i] valueForKey:@"id"] isEqualToValue:idToLookFor]) {
                return [categoryArray[i] valueForKey:@"product"];
            }
        }
        return nil;
    }