2014-02-15 34 views
0

我有這個數組的id和高度。如何從數組中獲取對象的值?

我怎樣才能得到一個給定的特定ID的高度?

像從數組中獲取review-1的值?這是「500px」?

謝謝。

ar=[]; 
ar.push({"id":"reiew-1","height":"500px"}); 

$.each(ar,function(index,value){ 

alert(value.height); // gets all the heights 

}); 

回答

0

你可以去functional並做這樣的事情:

ar=[ 
    {"id":"reiew-1","height":"500px"}, 
    {"id":"reiew-2","height":"600px"}, 
    {"id":"reiew-3","height":"700px"}, 
]; 

filterById=function(value){ 
    return function(o){ 
     return o["id"]===value; 
    };   
} 

getAttribute=function(value){ 
    return function(o){ 
     return o[value]; 
    } 
} 

ar.filter(filterById("reiew-1")).map(getAttribute("height")) 

哪個是容易對眼睛:]

這裏是fiddle

有關詳細信息(例如關於瀏覽器兼容性),這裏是MDN鏈接:Array.prototype.filter()Array.prototype.map()

+0

這對我工作感謝:) – user3260392

1

使用IF內環路條件

ar = []; 
ar.push({ 
    "id": "reiew-1", 
    "height": "500px" 
}); 

$.each(ar, function (index, value) { 
    if (value.id == 'reiew-1') { 
     alert(value.height); // gets all the heights 
     return false;//stop further looping of the array since the value you are looking for is found 
    } 
}); 
+0

感謝爲我工作:) – user3260392

1

所以,你只能使用JavaScript的方法來做到這一點的東西

var ar=[]; 
ar.push({"id":"reiew-1","height":"500px"}, {"id":"reiew-3","height":"500px"}); 

// function that filter and return object with selected id 
function getById(array, id){ 
    return array.filter(function(item){ 
    return item.id == id; 
    })[0].height || null; 
} 

// now you can use this method 
console.log(getById(ar, "reiew-1")) 

您可以使用此代碼玩,demo

+0

這是在正確的dircetion。但是他想要一個特定的'id'的「高度」;或許你把它添加到你的代碼中。 –

+0

抱歉))我失去了這個東西)) –