I have 1 array, one with a list of all my users with unique IDs. I have an object which contains contains a selected groups information. Part of that information is the owners ID. I'm trying to figure out, how do I get the users's information given the groups owner ID? For example, the student group object has an owner ID of 70, there's a user on my sites who's ID is 70...how do I match them up?
users:
[ {
id: 68
name: mike
domain: i:0#.f|admembers|mike.ca
email: mike.ca
isAdmin: False
}, etc etc ]
selectedGroup: {
name: Students
id: 78
description:
owner: 70
ownerIsUser: True
}
To find the first array element that matches a condition:Use the Array. find() method to iterate over the array. Check if each value matches the condition. The find method returns the first array element that satisfies the condition.
To search a particular object, we will use the Array prototype find method. This returns a value on a given criterion, otherwise, it returns 'undefined'. It takes two parameters, one required callback function and an optional object, which will be set as a value of this inside the callback function.
Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
You'll have to loop through users
:
var i = users.length,
ownerData;
while(i--) {
if(selectedGroup.owner == users[i].id) {
ownerData = users[i];
break;
}
}
Or you could use Array.filter()
:
var ownerData = users.filter(function(user) {
return user.id === selectedGroup.owner;
})[0];
In ECMAScript 6, you could use the native Array.find
method:
var selectedUser = users.find( function( user ){
return user.id === 70;
} );
Seeing as only the latest Firefox supports this for the moment, you could use a library like underscore.js:
var selectedUser = _.find( users, function( user ){
return user.id === 70;
} );
…or you could use a wrapper around the slightly less recent forEach
method:
var selectedUser;
users.forEach( function( user ){
if( user.id === 70 ){
selectedUser = user;
}
} );
But if you want to use script that'll support legacy browsers without using libraries, you'll need a for loop:
var selectedUser;
for( var i = 0; i < users.length; i++ ){
if( users[ i ].id === 70 ){
selectedUser = users[ i ];
break;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With