Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript array of objects search
"use strict";
var users = [
{
id: 1,
alias: "jdoe",
name: "John Doe"
},
{
id: 2,
alias: 'bking',
name: "Brian King"
}
];
/* Basic search */
var user = users.find(function (user) {
return user.id === 2;
});
console.log(user);
/* Search by known key */
function findById(arr, id) {
return arr.find(function (el) {
return el.id === id;
});
}
console.log(findById(users, 2));
/* Search by dynamic key */
function findByKey(arr, key, value) {
return arr.find(function (el) {
return el[`${key}`] === value;
});
}
console.log(findByKey(users, 'id', 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment