Xtian
Xtian

Reputation: 3587

match a variable to an element inside an array of objects?

i have a varable:

var name = "name";

this will be inside an array of objects i have:

    var all = [];
    $.each(results, function(i, item){
        all.push({
            rank: i + 1,
            username: item.TopicName,
            mentions: item.LastHourCount,
            totalcount: item.TotalCount,
            urlLg: item.LargeImageUrl,
            urlSm: item.SmallImageUrl,
            shortname: item.ShortName
        });

    });

I need to look through the array of objects and find the 'shortname' that matches the variable 'name'. the objects look like this:

Object[
  mentions: 21737
  rank: 2
  shortname: "name"
  totalcount: 59330
  urlLg: null
  urlSm: "http://i.cdn.turner.com/nba/nba/pulse/allstar/2012/img/images-small/howard.png"
  username: "lebron james"
],

once i find it set that to a variable: var showThis = all.[];

Inside the each function as it loops through the json file, is probably where to look for the name?

Upvotes: 0

Views: 1403

Answers (3)

Royi Namir
Royi Namir

Reputation: 148524

var t={};

$.each(all, function(i, item){

  if (item['shortname']=="name") {
    t=this;
    return false;
  }

});

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185913

Underscore.js solution:

var showThis = _.find( all, function ( elem ) {
    return elem.shortname === name;
});

Plain JavaScript solution:

var showThis = all.filter( function ( elem ) {
  return elem.shortname === name;
})[ 0 ];

Btw, .filter() is an ES5 array iteration method. The ES5 array iteration methods are not implemented in IE8 and older versions. (You can easily polyfill them though.)

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074168

I think I may be misunderstanding. If you just want to find the entry in all with a shortName matching name, then:

var match;
$.each(all, function() {
    if (this.shortName === name) {
        match = this;
        return false;
    }
});

That uses $.each to loop through the array. In the iterator callback, this will refer to the array element, so we just check this.shortName === name. The return false stops the each loop. If there's no match, match will keep its default value (undefined).

Or as a traditional for loop:

var match, index, entry;
for (index = 0; index < all.length; ++index) {
    entry = all[index];
    if (entry.shortName === name) {
        match = entry;
        break;
    }
});

Upvotes: 3

Related Questions