Skip to content

Instantly share code, notes, and snippets.

@atelic
Last active August 29, 2015 14:24
Show Gist options
  • Save atelic/e7d22a4174a23415fe7d to your computer and use it in GitHub Desktop.
Save atelic/e7d22a4174a23415fe7d to your computer and use it in GitHub Desktop.
Find with attribute in JS
// source: https://stackoverflow.com/questions/7176908/how-to-get-index-of-object-by-its-property-in-javascript
function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
}
var Data = [
{id_list: 2, name: 'John', token: '123123'},
{id_list: 1, name: 'Nick', token: '312312'}
];
//With this, not only can you find which one contains 'John' but you can find which contains the token '312312':
findWithAttr(Data, 'name', 'John'); // returns 0
findWithAttr(Data, 'token', '312312'); // returns 1
findWithAttr(Data, 'id_list', '10'); // returns undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment