Get/find javascript object by its parameter
-
25-10-2019 - |
سؤال
Considering I have an array of objects, and all objects represent something out of a database, thus they have an unique identifier.
Now I also have the ID and the correct array. How do I search each object in that array where the parameter 'id' equals my ID. (The point is, I don't know the internal identifier for that object. All I have is an ID and I need the entire object for description, last_user, created etc..)
Object
created: "2011-06-08 15:47:11"
description: "Something new.."
id: "1"
last_user: "1"
P.s. I have jQuery embedded, so if there's no default way, a jQuery function would suffice.
المحلول
$.grep() should do it. In the following example arr
is your array of objects. It will find the element that has an id
of 1
.
var obj = jQuery.grep(arr, function(el, i){
return el.id == 1;
})[0];
نصائح أخرى
You could loop through your array of objects, and check for each one if yourObject.id
is equal to the id
you are looking for. Then you'll be able to get the other fields, such as yourObject.created