19

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
 } 
1
  • see deepdash Commented Oct 29, 2022 at 9:48

6 Answers 6

29

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

5 Comments

var i = users.length, ownerData; I've never seen anything like this before. What is "i" here?
It's a quick way of looping through an array--i is initialized to the length of your users array, and it is decremented in the while loop below. When i reaches 0, the loop executes a final time and ends. It loops through the array in reverse.
I understand the index part, just not the ownerData part. Shouldn't it be declared separately like var i = x.length; var ownerData;
Oh. I'm using a comma to separate statements, thus removing the need to place them on individual lines (the whitespace is just for readability). It cuts down on the character count, and is a fairly standard way to declare multiple variables.
Oh I didn't know I could do it like that. Well I knew I could declare multiple empty variables like this var a,b,c,d; but had no clue I could initialize their values too. Cool, thanks for clearing that up.
11

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;
  }
};

Comments

3

Have a look at Underscore.js to trivialize this, like so:

_.findWhere(users, { id: 68 })

Naturally you could pass in a variable to match like:

_.findWhere(users, { id: selectedGroup.owner })

2 Comments

Bad form to include a library for one utility function. Maybe take a look at Underscore's implementation of findWhere and copy it out.
I would have suggested having a broader look at the Underscore library as a comment, as it is likely there is more to be gained, but I am not yet able to comment on questions.
1

You could just loop over the array to match that:

var match = function (array, matchfn) {
    var i;
    for (i in array) {
        if (matchfn(array[i])) {
            return array[i];
        }
    }
};

var user = match(users, function (u) { return u.id == 70; });

Comments

1

If you have to work with existing javascript objects, I think a brute-force solution is the only option:

var owner;
for(var i = 0; i < users.length; i++) {
    if (users[i].id == selectedGroup.id) {
        owner = users[i];
        break;
    }        
}

if (owner) {
    console.log(owner);
}

Depending on how you use it, it may be more efficient to restructure your first object so you can directly access a property:

var users = {
    "68": {
        id: 68,
        name: 'mike',
        domain: 'i: 0#.f | admembers | mike.ca',
        email: 'mike.ca',
        isAdmin: false
    }
};

var selectedGroup = {
    name: 'Students',
    id: 78,
    description: '',
    owner: 68,
    ownerIsUser: 'True'
};

var owner = users[selectedGroup.owner];

2 Comments

Holy crap...I really like the idea of restructuring the array into objects. It would probably require I rewrite my services but it might make things simpler later on.
I'm trying to restructure the object has selected but I'm not sure how to create a new properties from the loop. This is what I tried: jsfiddle.net/pGsc6
-1

You can also use Array.prototype.some to compare all of the objects properties to see if they contain equal values.

function haveSameValues(oneObject, anotherObject) {
  var hasDifferentKeyValues = Object.keys(oneObject).some(function(key){ 
    return oneObject[key] !== anotherObject[key]
  });

  return !hasDifferentKeyValues;
}

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.