Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.grep to return property after match

I couldn't find any instances where this was being done so I'm asking you brainy people out there if there's a nice easy way to do what I'm wanting.

Trying to map two arrays together. One array has a list of the IDs (Foos), and the other array has all the properties (bars) for those IDs. Want to keep everything in my angular controller.

Here's a snippet. I'm trying to match on ID and map into the Name property.

$scope.Foos = $.map($scope.Foos, function (foo) {
                            return {
                                ID: foo.ID,
                                Name: $.grep($scope.bars, function(b){
                                    return b.ID === foo.ID;
                                }).Name,
                                Property: $.grep($scope.bars, function(b){
                                    return b.ID === foo.ID;
                                }).Property
                                };
                            });

What I understand is that $.grep will return the object based on the criteria, can I then call properties of that returned object?

Update:

Foos is ID (guid) Bars is ID(guid), Name & Property

like image 803
markokstate Avatar asked Oct 10 '15 00:10

markokstate


1 Answers

$.grep returns an array, not an object, so to do what you are wanting you would need to do something like:

Name: $.grep($scope.bars, function(b){
            return b.ID === foo.ID;
      })[0].Name

The problem here however is if there is no match , $.grep will return an empty array and you will end up throwing an error trying to get the first element from that empty array.

You really should look the properties up first, not while trying to build a more complex object

Something like:

$scope.Foos = $.map($scope.Foos, function (foo) {
    // first filter the array
    var bars = $.grep($scope.bars, function (b) {
        return b.ID === foo.ID;
    });
    // now test we have result, if not make it ... empty string???
    var name = bars.length ? bars[0].Name : '';

    // do similar for `Property`

    return {
        ID: foo.ID,
        Name: name,
        ......
    };
});

This could also be modified to have some utility functions like getNameFromBars() and put the $.grep in there and return value found or the default.

If you wanted to get rid of jQuery you could use Array.prototype.map() and Array.prototype.filter() to replace $.map and $.grep.

Also $filter could be used.

like image 171
charlietfl Avatar answered Sep 19 '22 07:09

charlietfl