0

I have this array with several id's and heights.

How can i get a hight of a specific id given?

like get the value of review-1 from the array? which is "500px"?

thanks.

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

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

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

});

3 Answers 3

1

Use an if condition within the loop

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
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

So you can use only javascript methods to do this things

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"))

You can play with this code, demo

2 Comments

That's in the right dircetion. But he wants the "height" of a specific id ;) Perhaps you add that to your code.
sorry)) I lost this thing))
0

You could go functional and do something like this:

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"))

Which is easy on the eyes :]

Here is the fiddle

For more information (e.g. about browser compatibility), here are the MDN links:Array.prototype.filter() and Array.prototype.map()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.