-3

How to get an id from array of object {id, username, email}, I have username as string and I need an id from object which has that username

Michael Benford
  • 14,044
  • 3
  • 60
  • 60

3 Answers3

0

If you are using jQuery...

Referencing this link:

Find object by id in an array of JavaScript objects

you can do

var result = $.grep(myArray, function(e){ return e.username == username; });

console.log(result.id);

You can replace myArray with your array of objects.

result.id should give you the id of the object you are looking for.

Community
  • 1
  • 1
Seyong Cho
  • 1,067
  • 1
  • 10
  • 29
0

No need for any frameworks - just use javascript's filter method.

var elSearch = document.getElementById('searchName');
var elResultDisplay = document.getElementById('result');

var search = function() {
    // username to search for
    var searchName = elSearch.value;
    var hitId;

    var users = [
      {id: 1, username: 'ted', email: 'ted@example.com'},
      {id: 2, username: 'robin', email: 'robin@example.com'},
      {id: 3, username: 'barney', email: 'barney@example.com'}
    ];

    // filter will return an array with matching items
    var hit = users.filter(function (user) {
      return user.username === searchName;
    });

    // check if there an item matched the search expression
    if (hit.length) {
      hitId = hit[0].id;
      elResultDisplay.innerHTML = hitId;
    } else {
      elResultDisplay.innerHTML = 'no match';
    }
};
<pre>
    var users = [
      {id: 1, username: 'ted', email: 'ted@example.com'},
      {id: 2, username: 'robin', email: 'robin@example.com'},
      {id: 3, username: 'barney', email: 'barney@example.com'}
    ];
</pre>

<input id="searchName" type="text" />
<button onclick="search()">Search</button>

<p id="result"></p>
naeramarth7
  • 6,030
  • 1
  • 22
  • 26
-1

You can just use underscore.js, I'm assuming you are using javascript.

_.findWhere(array, {username: "Velijko"});

That will give you the entire object, you can then just get the id. If using Java, you can do similar stuff with Guava libraries.

farolfo
  • 388
  • 1
  • 4
  • 13