1

Possible Duplicate:
Find object by id in array of javascript objects

I can do this to get the particular hash from an array of hash where a particular key has a certain value. For example, if I want to get the name value of hash where key id is 2, I can do this:

array = [{:id => 1, :name => "A"}, 
         {:id => 3, :name => "C"}, 
         {:id => 2, :name => "B"}]
id_2_hash = array.detect {|a| a[:id] == 2}
=> {:id => 2, :name => "B"}
id_2_hash[:name]
=> "B"

I want the same to be done to a JSON object like this:

[
  {
    'id': 1,
    'name': 'A'
  },
  {
    'id': 3,
    'name': 'C'
  },
  {
    'id': 2,
    'name': 'B'
  }
]

How can I do this in Javascript/Jquery?

Community
  • 1
  • 1
rubyprince
  • 17,559
  • 11
  • 64
  • 104

3 Answers3

1

Use [].filter();

    /**
     * @param {Function} fn is Callback-function
     * @param {Object} Object to use as this when executing callback
     * @link {forEach}
     * @return {Array} Creates a new array with all elements that pass the test implemented by the provided function
     * @edition ECMA-262 5th Edition, 15.4.4.20
    */
    (function($) {
        'use strict';

        if(!$.filter) {
            $.filter = function(fn, object) {
                var length = this.length,
                    array = [],
                    i = -1;

                while(i++ < length) {
                    if(i in this && fn.call(object, this[i], i, this)) {
                        array.push(this[i]);
                    }
                }
                return array;
            };
        }

    })(Array.prototype);
nikc.org
  • 16,462
  • 6
  • 50
  • 83
Alexander Abashkin
  • 1,187
  • 4
  • 13
  • 18
0
var items = [
  {
    'id': 1,
    'name': 'A'
  },
  {
    'id': 3,
    'name': 'C'
  },
  {
    'id': 2,
    'name': 'B'
  }
];
console.log(items.filter(function(v) {
  return v.id == 2;
})[0].name);

UPDATE: Note that Array#filter cannot work on IE 8 and below

qiao
  • 17,941
  • 6
  • 57
  • 46
  • 1
    If you're going to point someone at a new feature like `Array#filter`, you really need to tell them how new it is (added in ECMAScript5) and that it's not supported by the browser versions something like 50% of people are currently using. (It's not even in IE9 yet.) – T.J. Crowder Jan 02 '12 at 13:09
  • @T.J.Crowder Thanks for pointing out. BTW, it seem that IE9 supports `Array#filter`, according to this table http://kangax.github.com/es5-compat-table/ – qiao Jan 02 '12 at 13:22
  • MDN also says it's available in IE9: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter#Browser_compatibility – nikc.org Jan 02 '12 at 13:28
  • @T.J.Crowder I'll have to take your word for it, as I'm on a mac right now and have no way to confirm one way or the other. (Just noticed that on MDN it says: Based on Kangax's compat tables. Duh.) – nikc.org Jan 02 '12 at 13:42
  • 1
    @nikc & qiao: I've removed my comments above, `Array#filter` **is** supported in IE9. There's something strange about jsbin! This shows that IE9 *doesn't* have it: http://jsbin.com/otadil But kangax's page and [my own standalone test](http://www.crowdersoftware.com/filter.html) show that it does. I find this **extremely** odd. The jsbin page works fine in Chrome, so it's not just a blatant error in my test on that page. Very, very strange. – T.J. Crowder Jan 02 '12 at 13:51
  • 1
    @nikc & qiao: I've [reported it](https://github.com/remy/jsbin/issues/119) to Remy. – T.J. Crowder Jan 02 '12 at 14:12
  • 1
    @nikc.org & qiao: ***Doh***! Somehow, jsbin.com had ended up being shown in the (rather mis-named) "Compatibility View". *sigh* When shown in IE9 proper, works as expected. – T.J. Crowder Jan 12 '12 at 14:15
0

heare is a simple sollution, but i'm sure there are better.. Save to a .js file and run. If you don't use windows, remove the WScript.Echo to test it. Mind you, i don't use Filter here cause not supported in all versions of javascript.

var obj = [{ 
    'id': 1,
    'name': 'A'
  },
  {
    'id': 3,
    'name': 'C'
  },
  {
    'id': 2,
    'name': 'B'
  }
]

for (i=0;i<obj.length;i++){
  if (obj[i].id==2){
    WScript.Echo(obj[i].name);
  }
}
peter
  • 41,770
  • 5
  • 64
  • 108