Thursday, October 29, 2020

Javascript - writing generic function for search

We can achieve this using helper function 


function findInDict(dict, predicate) 

{

    for (var prop in dict) {

        if (dict.hasOwnProperty(prop) && predicate(dict[prop], prop, dict)) {

            return prop;

        }

    }

    return null;

  };

}


You can use this helper function:


function findInDict(dict, predicate) 

{

    for (var prop in dict) {

        if (dict.hasOwnProperty(prop) && predicate(dict[prop], prop, dict)) {

            return prop;

        }

    }

    return null;

  };

}

Then perform the search:


// find property on main dictionary

var prop = findInDict(dict, function(value, name) {

    // name is property name

    // value is property value

    return value[0].socketid == 'bVLmrV8I9JsSyON7AAAA';

});


if (prop === null) {

    // prop doesn't exist, so create one?

}



References:

https://stackoverflow.com/questions/24605893/searching-an-id-in-an-array-of-dictionary-in-javascript


No comments:

Post a Comment