Last active
May 27, 2021 06:34
-
-
Save mtvbrianking/03662be3a18d5d564c416c9cad0128ae to your computer and use it in GitHub Desktop.
Javascript array of objects search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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