Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Last active May 27, 2021 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/03662be3a18d5d564c416c9cad0128ae to your computer and use it in GitHub Desktop.
Save mtvbrianking/03662be3a18d5d564c416c9cad0128ae to your computer and use it in GitHub Desktop.
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