2012-01-02 79 views
1

可能重複:
Find object by id in array of javascript objects等效的JavaScript/Ruby的語法的jQuery

我可以做到這一點,以獲得從一個數組的哈希,其中特定鍵具有一定的價值特定哈希。例如,如果我想獲得散列結果,其中關鍵id是2的name價值,我可以這樣做:

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" 

我想同樣做一個JSON對象是這樣的:

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

我該如何在Javascript/JQuery中做到這一點?

+0

您是使用下劃線還是等效函數庫? – tokland 2012-01-02 16:17:11

回答

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:注意陣列#過濾器不能在IE 8及以下

+1

如果您要指定某人使用像Array#filter這樣的新功能,您確實需要告訴他們它有多新(在ECMAScript5中添加),並且它不受瀏覽器版本支持,例如50%的人目前正在使用。 (它甚至不在IE9中。) – 2012-01-02 13:09:16

+0

@ T.J.Crowder感謝您指出。順便說一句,它似乎IE9支持'陣列#過濾器',根據此表http://kangax.github.com/es5-compat-table/ – qiao 2012-01-02 13:22:31

+0

MDN還表示,它在IE9中可用:https://developer.mozilla。 org/en/JavaScript/Reference/Global_Objects/Array/filter#Browser_compatibility – 2012-01-02 13:28:56

0

heare工作是一個簡單的sollution,但我敢肯定有更好的.. 保存到一個.js文件並運行。 如果您不使用Windows,請移除WScript.Echo以對其進行測試。 請注意,我不使用過濾器,因爲在所有版本的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); 
    } 
} 
1

使用[] .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);