如何在数组中搜索对象

时间:2015-04-10 19:38:19

标签: javascript

如何从对象{id,username,email}数组中获取id,我将用户名作为字符串,我需要来自具有该用户名的对象的id

3 个答案:

答案 0 :(得分:0)

如果你正在使用jQuery ......

参考此链接:

Find object by id in an array of JavaScript objects

你可以做到

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

console.log(result.id);

您可以将myArray替换为您的对象数组。

result.id应该为您提供您要查找的对象的ID。

答案 1 :(得分:0)

不需要任何框架 - 只需使用javascript的filter方法。

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>

答案 2 :(得分:-1)

你可以使用underscore.js,我假设你使用的是javascript。

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

那将为您提供整个对象,然后您就可以获得ID。 如果使用Java,您可以使用Guava库执行类似的操作。