簡體   English   中英

如何從數組中獲取對象的值?

[英]how can i get an object's value from an array?

我有這個數組有幾個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

});

在循環中使用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
    }
});

所以你只能使用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"))

您可以使用此代碼演示

你可以去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"))

這對眼睛來說很容易:]

這是小提琴

有關更多信息(例如,有關瀏覽器兼容性),以下是MDN鏈接: Array.prototype.filter()Array.prototype.map()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM