How to determine if Javascript array contains an object with an attribute that equals a given value?
2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.
There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}
Array.includes() to find object in array
Array.includes
compares by object identity just like obj === obj2
, so sadly this doesn't work unless the two items are references to the same object. You can often use Array.prototype.some()
instead which takes a function:
const arr = [{a: 'b'}]console.log(arr.some(item => item.a === 'b'))
Javascript: Using `.includes` to find if an array of objects contains a specific object
includes
essentially checks if any element ===
the element you're searching for. In case of objects, ===
means literally the same object, as in the same reference (same place in memory), not the same shape.
var a1 = { name: 'a' }var a2 = { name: 'a' }
console.log(a1 === a2) // false because they are not the same object in memory even if they have the same data
How do I check if an array includes a value in JavaScript?
Modern browsers have Array#includes
, which does exactly that and is widely supported by everyone except IE:
console.log(['joe', 'jane', 'mary'].includes('jane')); //true
How to check if array of object contains a string
Since you need to check the object property value in the array, you can try with Array.prototype.some()
:
The
some()
method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
let arr = [ { name: 'Jack', id: 1 }, { name: 'Gabriel', id: 2 }, { name: 'John', id: 3 }]var r = arr.some(i => i.name.includes('Jack'));console.log(r);
How to determine if object is in array
Use something like this:
function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i] === obj) {
return true;
}
}
return false;
}
In this case, containsObject(car4, carBrands)
is true. Remove the carBrands.push(car4);
call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:
function containsObject(obj, list) {
var x;
for (x in list) {
if (list.hasOwnProperty(x) && list[x] === obj) {
return true;
}
}
return false;
}
This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.
Check if object value exists within a Javascript array of objects and if not add a new object to array
I've assumed that id
s are meant to be unique here. some
is a great function for checking the existence of things in arrays:
const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
function add(arr, name) { const { length } = arr; const id = length + 1; const found = arr.some(el => el.username === name); if (!found) arr.push({ id, username: name }); return arr;}
console.log(add(arr, 'ted'));
Related Topics
Best Way to Highlight Current Page in Rails 3? - Apply a CSS Class to Links Conditionally
Differencebetween Integer and Fixnum
Rails - Sort by Join Table Data
(Ruby) Getting Net::Smtp Working with Gmail...
What's the Point of Argv in Ruby
Why Does Ruby /[[:Punct:]]/ Miss Some Punctuation Characters
Welcome/Home Page in Ruby on Rails - Best Practice
How to Compare Versions in Ruby
In Rails, Display Time Between Two Dates in English
Spinning Background Tasks in Rails
Gem.Source_Index Is Deprecated, Use Specification. Should I Re-Install Gem or Rails
Change the Binding of a Proc in Ruby
What's the Difference Between Colon ":" and Fat Arrow "=>"
How to Sort a Ruby Hash by Number Value
How to Pass a Parameter for Gem Installation When I Run Bundle Install