Reputation: 10844
I have a javascript json result list - self.data.allOrganizationsList
self.data.allOrganizationsList contains list of organization whose properties are
customentityaccess, id, isLabsAccessAllowed, memberCount, organizationname, organizationwebsite
i want to access an organization object which has id = 402881702121fec10121520080930001
I am trying to get this from the below statement, but since each item in the list is an object, i am unable to get the desired result.
self.data.allOrganizationsList.id['402881702121fec10121520080930001']`
//(or)
self.data.allOrganizationsList["id"]['402881702121fec10121520080930001']
Other alternative is to use the $.each(self.data.allOrganizationList, function(index, item)).
But can i achieve the above result without iterating the - self.data.allOrganizationList
From the $.grept()
var myvar = $.grep(response.permissionedOrganizations, function(v) {
return v.id === '40288170227c142201227eb56c5c000a';
})[0];
console.log(myvar);
displays undefined in console. Am i missing something.
Upvotes: 0
Views: 2500
Reputation: 20027
If you need to search more than one object based on the value, you can simply iterate the list once:
for (var i in list) {
var id = list[i].id;
my_table[id] = list[i]; // for unique ids
}
For non unique ids make my_table
as an associative array of arrays:
if (!my_table[id]) my_table[id] = [list[i]];
else my_table[id].push(list[i]);
In the latter case my_table['12399123'] can return an array of results.
Upvotes: 0
Reputation: 1471
jQuery.grep( array, function(elementOfArray, indexInArray) [, invert] )
Finds the elements of an array which satisfy a filter function. The original array is not affected. check
Upvotes: 2
Reputation: 154818
With your structure, you want $.grep
to filter out the correct element:
var arr = [
{id: 1, value: 2},
{id: 3, value: 4}
];
$.grep(arr, function(v) { return v.id === 3; })[0]; // second element
Note that this does iterating behind the scenes - there's not a way to get the correct element by using [key]
notation as that's not how your structure is defined.
Upvotes: 4
Reputation: 30082
If it's an array, then it is not keyed by the id, so you need to loop over each item and check the id property, as you described above.
For you to be able to check by id it would have to be something like:
var allOrganizationsList =
{
"id1": {
"memberCount": 1
},
"id2": {
"memberCount": 2
}
};
allOrganizationsList["id1"].memberCount;
Upvotes: 0