1337

I have an array like

vendors = [{
    Name: 'Magenic',
    ID: 'ABC'
  },
  {
    Name: 'Microsoft',
    ID: 'DEF'
  } // and so on...
];

How do I check this array to see if "Magenic" exists? I don't want to loop, unless I have to. I'm working with potentially a couple of thousand records.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
David Lozzi
  • 14,697
  • 9
  • 28
  • 44

28 Answers28

2078

There isn't any need to reinvent the wheel loop, at least not explicitly (using arrow functions, modern browsers only):

if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
  /* vendors contains the element we're looking for */
}

or, better yet, use some as it allows the browser to stop as soon as one element is found that matches, so it's going to be faster:

if (vendors.some(e => e.Name === 'Magenic')) {
  /* vendors contains the element we're looking for */
}

or the equivalent (in this case) find:

if (vendors.find(e => e.Name === 'Magenic')) {
  /* same result as above, but a different function return type */
}

And you can even get the position of that element by using findIndex:

const i = vendors.findIndex(e => e.Name === 'Magenic');
if (i > -1) {
  /* vendors contains the element we're looking for, at index "i" */
}

And if you need compatibility with lousy browsers then your best bet is:

if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
  /* vendors contains the element we're looking for */
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CAFxX
  • 28,060
  • 6
  • 41
  • 66
  • 4
    @CAFxX How would you get the index when found? is this even a possibility or would a loop work better to get the index? – Echtniet Apr 03 '18 at 20:44
  • 4
    @Echtniet if you need the index then vendors.findIndex will give you the index of the first matching element. If instead you need the value then either vendors.find will give the first matching element, or vendors.filter will give you all matching elements. You may want to refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array – CAFxX Apr 04 '18 at 22:05
  • 2
    Why is `some` *better yet* ? – 7hibault Apr 19 '19 at 16:29
  • 21
    @7hibault because `some` can short circuit once an object with `name === "Magenic"` is found. With `filter`, it will check each item till the end of the array and create a new array items which match the condition, then check the `length` – adiga May 14 '19 at 14:03
  • 8
    Lots of comments about `.some`. It's 2019, use `.some` and use Polyfills to support lousy browsers and move on with you life... polyfill.io/v3/url-builder. The only thing I can see is that if you can't support arrow functions then it's as simple as the Polyfill I mentioned and: `arr.some(function(i) { return i.Name === "Magenic" })` – maxshuty Dec 24 '19 at 12:37
  • Side note: I [checked on CanIUse](https://caniuse.com/mdn-javascript_builtins_array_some), and `.some` itself is widespread. Even IE supports it, except for archaic versions. – Egor Hans Nov 23 '21 at 08:02
  • To add to @CAFxX .some solution, you can use an external variable with Array.some like this: `const externalVariable = 'My custom Name'; if (vendors.some(function(element) { e.Name === this}, externalVariable)) { /* vendors contains the element we're looking for */ }` – lauri108 Nov 24 '21 at 03:25
  • How do I get the index after if that element does exist? – Cyber Avater Mar 25 '22 at 15:57
  • @CyberAvater https://stackoverflow.com/questions/8217419/how-to-determine-if-javascript-array-contains-an-object-with-an-attribute-that-e/8217584?noredirect=1#comment86332057_8217584 – CAFxX Mar 27 '22 at 03:05
  • many many thanks this method saved me. I was trying about 48 hour to solve my problem. finally it's solved by this if (vendors.filter(e => e.Name === 'Magenic').length > 0) { /* vendors contains the element we're looking for */ } – Shibbir Ahmad Apr 13 '22 at 05:38
  • Shall start a petition to accept this as selected answer. – robinHood013 Feb 14 '23 at 10:29
379

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;
    }
}
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
  • 5
    No problem. Keep in mind that [Keith's solution](http://stackoverflow.com/questions/8217419/how-to-determine-if-json-array-contains-object/8217459#8217459) is also very viable and saves you from looping. – Alex Turpin Nov 21 '11 at 19:41
  • 2
    You don't need a flag if all you need to know is whether or not "something" is in, you can just check the value of the scan index with the size of array. For this to work the index var needs to be declared before the for statement of course. – Alex Oct 29 '14 at 21:05
  • 7
    These options seem to work now: vendors.forEach, vendors.filter, vendors.reduce – David Lozzi Aug 05 '16 at 13:45
  • 1
    what about JSON.stringify(vendors).indexOf('Magenic') !== -1 – Last Breath Mar 14 '19 at 12:23
  • 4
    @LastBreath that could result in a false positive quite easily if `'Magenic'` is somewhere else in the object – Alex Turpin Mar 15 '19 at 16:22
  • 1
    WARNING: The wrong answer has been marked as correct. – arled Mar 24 '21 at 17:17
  • @arled This is the answer that originally solved this for OP, and it's valid to let it keep the credit for that. Especially since it mentions in bold that it's outdated, linking to the modern answer. – Egor Hans Nov 23 '21 at 17:01
  • @EgorHans It's also OK to move the check mark when things change. Luckily SO fixed this issue by unpinning the accepted answer so it's less likely to confuse people who didn't scroll down in the past. – ggorlen Jul 13 '22 at 16:26
  • "2018 edit..." -- you can simply update the answer when things change. "There is no "magic" way to check for something in an array without a loop" -- `some` is magic! – ggorlen Jul 13 '22 at 16:27
207

No loop necessary. Three methods that come to mind:

Array.prototype.some()

This is the most exact answer for your question, i.e. "check if something exists", implying a bool result. This will be true if there are any 'Magenic' objects, false otherwise:

let hasMagenicVendor = vendors.some( vendor => vendor['Name'] === 'Magenic' )

Array.prototype.filter()

This will return an array of all 'Magenic' objects, even if there is only one (will return a one-element array):

let magenicVendors = vendors.filter( vendor => vendor['Name'] === 'Magenic' )

If you try to coerce this to a boolean, it will not work, as an empty array (no 'Magenic' objects) is still truthy. So just use magenicVendors.length in your conditional.

Array.prototype.find()

This will return the first 'Magenic' object (or undefined if there aren't any):

let magenicVendor = vendors.find( vendor => vendor['Name'] === 'Magenic' );

This coerces to a boolean okay (any object is truthy, undefined is falsy).


Note: I'm using vendor["Name"] instead of vendor.Name because of the weird casing of the property names.

Note 2: No reason to use loose equality (==) instead of strict equality (===) when checking the name.

boxtrain
  • 2,458
  • 1
  • 11
  • 20
  • 11
    It's useful to point out that under the hood, these are all looping. These are also all slower computationally than simply for looping and performing operations. – ThePartyTurtle Jan 18 '17 at 19:31
  • May as well go share that love here: http://stackoverflow.com/questions/21748670/why-are-native-array-functions-are-so-much-slower-then-loop so more people like me don't navigate to that old page and make assumptions. – ThePartyTurtle Jan 19 '17 at 15:55
  • @ThePartyTurtle: True!! Though developer hours are often more expensive compared to users' CPU hours (and less code is often nice). – Herbert Van-Vliet Sep 14 '22 at 13:37
81

The accepted answer still works but now we have an ECMAScript 6 native methods [Array.find][1] and [Array.some][2] to achieve the same effect.

Array.some

Use some If you only want to determine if an element exists i.e. you need a true/false determination.

Quoting MDN:

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

Array.find

Use find if you want to get the matched object from array else returns undefined.

Quoting MDN:

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

var arr = [
  {
    id: 21,
    label: 'Banana',
  },
  {
    id: 22,
    label: 'Apple',
  }
]

/* note : data is the actual object that matched search criteria 
  or undefined if nothing matched */

var data = arr.find(function(ele) {
    return ele.id === 21;
});

if (data) {
    console.log('found');
    console.log(data); // This is entire object i.e. `item` not boolean
}


/* note : doesExist is a boolean thats true or false depending on of whether the data was found or not */
var doesExist = arr.some(function(ele) {
    return ele.id === 21;
});


See my jsfiddle link There is a polyfill for IE provided by mozilla

TeaCoder
  • 1,958
  • 13
  • 13
  • 2
    Could be shorter if you just do `return ele.id == '2'`, but +1 for a good ES6 solution. – Lye Fish Mar 05 '16 at 01:47
  • Good to have fresh answer :) Just wondering if performance are better or not than answers above... – Emidomenge Jul 22 '16 at 07:45
  • I think it is important to point out that the return value of 'data' (when ele.id matches an id, such as '21') is going to be the array item itself (in this case, the whole item object). If the expectation was that the data variable result would be 'true' or 'false' instead of a falsy value, you would be sorely disappointed. – adamgede Mar 10 '17 at 02:01
  • Thx! My task was a bit different. Get the index of Object in the Array => `push if <0 || splice(index, 1)` here is my a bit updated code: `const index = this.selected.indexOf(this.selected.find(s => s.id == passedObj.id))` – Leonid Zadorozhnykh Aug 24 '17 at 08:27
  • This code only works if `return ele.id === 21;`; it's a number, not a string. –  Dec 01 '21 at 16:00
52

Here's the way I'd do it

const found = vendors.some(item => item.Name === 'Magenic');

array.some() method checks if there is at least one value in an array that matches criteria and returns a boolean. From here on you can go with:

if (found) {
// do something
} else {
// do something else
}
Mirza Leka
  • 651
  • 7
  • 11
30

Unless you want to restructure it like this:

vendors = {
    Magenic: {
      Name: 'Magenic',
      ID: 'ABC'
     },
    Microsoft: {
      Name: 'Microsoft',
      ID: 'DEF'
    } and so on... 
};

to which you can do if(vendors.Magnetic)

You will have to loop

Keith.Abramo
  • 6,952
  • 2
  • 32
  • 46
28

A JavaScript array has two methods, the some and every methods that return a Boolean and can help you achieve this.

I think some would be most appropriate for what you intend to achieve.

vendors.some(vendor => vendor['Name'] !== 'Magenic')

Some validates that any of the objects in the array satisfies the given condition.

vendors.every(vendor => vendor['Name'] !== 'Magenic')

every validates that all the objects in the array satisfies the given condition.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Akinjiola Toni
  • 658
  • 7
  • 9
26

As per the ECMAScript 6 specification, you can use findIndex.

const magenicIndex = vendors.findIndex(vendor => vendor.Name === 'Magenic');

magenicIndex will hold either 0 (which is the index in the array) or -1 if it wasn't found.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lucas Bento
  • 1,212
  • 4
  • 17
  • 17
  • 1
    Just to make people aware that 0 would still match as a false result if that was used as the condition. For this reason I think find() is better as you get a more _logical_ truthy evaluation. – dhj Apr 04 '18 at 12:32
  • Not only what @dhj mentioned, but also, it might be found at a later index (1, 2 etc). As such, you'll need to check whether the index is at least 0, so most solutions that directly yield a boolean-usable value will be more elegant. – Egor Hans Nov 24 '21 at 08:00
23

As the OP has asked the question if the key exists or not:

A more elegant solution that will return a Boolean using the ES6 reduce function can be:

const magenicVendorExists = vendors.reduce((accumulator, vendor) => (accumulator||vendor.Name === "Magenic"), false);

Note: The initial parameter of reduce is a false and if the array has the key it will return true.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jay Chakra
  • 1,481
  • 1
  • 13
  • 29
14

You cannot without looking into the object really.

You probably should change your structure a little, like

vendors = {
    Magenic:   'ABC',
    Microsoft: 'DEF'
};

Then you can just use it like a lookup-hash.

vendors['Microsoft']; // 'DEF'
vendors['Apple']; // undefined
jAndy
  • 231,737
  • 57
  • 305
  • 359
12
const check = vendors.find((item)=>item.Name==='Magenic')

console.log(check)

Try this code.

If the item or element is present then the output will show you that element. If it is not present then the output will be 'undefined'.

11

Testing for array elements:

JavaScript offers array functions which allow you to achieve this relatively easily. They are the following:

  1. Array.prototype.filter: Takes a callback function which is a test, the array is then iterated over with is callback and filtered according to this callback. A new filtered array is returned.
  2. Array.prototype.some: Takes a callback function which is a test, the array is then iterated over with is callback and if any element passes the test, the boolean true is returned. Otherwise false is returned

The specifics are best explained via an example:

Example:

vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    } //and so on goes array...
];

// filter returns a new array, we instantly check if the length
// is longer than zero of this newly created array
if (vendors.filter(company => company.Name === 'Magenic').length ) {
  console.log('I contain Magenic');
}

// some would be a better option then filter since it directly returns a boolean
if (vendors.some(company => company.Name === 'Magenic')) {
  console.log('I also contain Magenic');
}

Browser support:

These 2 function are ES6 function, not all browsers might support them. To overcome this you can use a polyfill. Here is the polyfill for Array.prototype.some (from MDN):

if (!Array.prototype.some) {
  Array.prototype.some = function(fun, thisArg) {
    'use strict';

    if (this == null) {
      throw new TypeError('Array.prototype.some called on null or undefined');
    }

    if (typeof fun !== 'function') {
      throw new TypeError();
    }

    var t = Object(this);
    var len = t.length >>> 0;

    for (var i = 0; i < len; i++) {
      if (i in t && fun.call(thisArg, t[i], i, t)) {
        return true;
      }
    }

    return false;
  };
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
9

Simplest method so far:

if (vendors.findIndex(item => item.Name == "Magenic") == -1) {
  //not found item
} else {
  //found item 
}
Zach Jensz
  • 3,650
  • 5
  • 15
  • 30
nhCoder
  • 451
  • 5
  • 11
7

My approach to solving this problem is to use ES6 and creating a function that does the check for us. The benefit of this function is that it can be reusable through out your project to check any array of objects given the key and the value to check.

ENOUGH TALK, LET'S SEE THE CODE

Array

const ceos = [
  {
    name: "Jeff Bezos",
    company: "Amazon"
  }, 
  {
    name: "Mark Zuckerberg",
    company: "Facebook"
  }, 
  {
    name: "Tim Cook",
    company: "Apple"
  }
];

Function

const arrayIncludesInObj = (arr, key, valueToCheck) => {
  return arr.some(value => value[key] === valueToCheck);
}

Call/Usage

const found = arrayIncludesInObj(ceos, "name", "Tim Cook"); // true

const found = arrayIncludesInObj(ceos, "name", "Tim Bezos"); // false
rotimi-best
  • 1,852
  • 18
  • 29
7

2021 Solution*

Lodash .some (documentation) is a clean solution, if you use the _matchesProperty (documentation) shorthand:

_.some(VENDORS, ['Name', 'Magenic'])

Explanation

This will iterate through the VENDORS Array, looking for an element Object with the Name key having a value of the String 'Magenic'. Once it finds this element, it returns true and stops iterating. If it doesn't find the element after looking through the entire Array, it returns false.

Code snippet

const VENDORS = [{ Name: 'Magenic', ID: 'ABC' }, { Name: 'Microsoft', ID: 'DEF' }];

console.log(_.some(VENDORS, ['Name', 'Magenic'])); // true
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>

* Note that this uses the popular Lodash library to achieve the simplest/shortest possible solution. I'm offering this as an alternative to the existing vanilla JavaScript solutions, for those who are interested.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JBallin
  • 8,481
  • 4
  • 46
  • 51
6

Correct me if I'm wrong...

I could have used the forEach method like this,

var found = false;
vendors.forEach(function(item){
    if(item.name === "name"){
        found = true;
    }
});

Nowadays I'm used to it, because of its simplicity and self-explanatory word.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nerdy Sid
  • 332
  • 5
  • 14
6

Functions map, filter, find, and similar are slower than the simple loop. For me they also less readable than the simple loop and harder to debug. Using them looks like a kind of irrational ritual.

Better have something like this:

 arrayHelper = {
     arrayContainsObject: function (array, object, key){
         for (let i = 0; i < array.length; i++){
            if (object[key] === array[i][key]){
                 return true;
            }
         }
         return false;
     }
     
   };

And use it like this with given OP example:

    vendors = [{
    Name: 'Magenic',
    ID: 'ABC'
     },
     {
    Name: 'Microsoft',
    ID: 'DEF'
     } 
  ];

let abcObject = {ID: 'ABC', Name: 'Magenic'};

let isContainObject = arrayHelper.arrayContainsObject(vendors, abcObject, 'ID');
Yuriy N.
  • 4,936
  • 2
  • 38
  • 31
  • 3
    map, filter, find are more readable and code is also smaller and quicker to write – Sunil Kumar Singh Jun 02 '21 at 20:37
  • Why are they much slower than the simple loop? As far as I know, they'll have the same time complexity as their simple loop equivalents. For example, both of your codes look like O(n) to me. – Michael Fulton Jun 14 '21 at 22:18
  • above method `arrayContainsObject` is supposed to be a library method that you write once and forget. You actually can write it using array functions if you prefer. And nothing can beat `arrayHelper.arrayContainsObject` from the point of readability. – Yuriy N. Aug 13 '21 at 09:36
  • 1
    @Michael Fulton https://leanylabs.com/blog/js-forEach-map-reduce-vs-for-for_of/ This article with a benchmark states for loops 3 times faster. – Yuriy N. Jan 20 '22 at 12:35
  • Why not make it return the index at which the property is found, this will cover both the question and the findinex mentioned in other answers and requested in other comments? – Julio Spinelli Feb 17 '22 at 16:07
  • 1
    @JulioSpinelli. Agree, why not? But then we should rename our method to be like `findIndexOfObject`. So, better to have them both. – Yuriy N. Feb 17 '22 at 18:53
  • bad practice instead use my answer – nhCoder Jun 18 '22 at 17:21
6

You have to loop. There isn't any way around it.

function seekVendor(vendors, name) {
  for (var i=0, l=vendors.length; i<l; i++) {
    if (typeof vendors[i] == "object" && vendors[i].Name === name) {
      return vendors[i];
    }
  }
}

Of course you could use a library like linq.js to make this more pleasing:

Enumerable.From(vendors).Where("$.Name == 'Magenic'").First();

(see jsFiddle for a demo)

I doubt that linq.js will be faster than a straightforward loop, but it certainly is more flexible when things get a little more complicated.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tomalak
  • 332,285
  • 67
  • 532
  • 628
5

If you're using jQuery you can take advantage of grep to create array with all matching objects:

var results = $.grep(vendors, function (e) {
    return e.Name == "Magenic";
});

and then use the results array:

for (var i=0, l=results.length; i<l; i++) {
    console.log(results[i].ID);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eitan
  • 367
  • 3
  • 8
3

You can use Lodash. If the Lodash library is too heavy for your application, consider chunking out unnecessary functions not used.

let newArray = filter(_this.props.ArrayOne, function(item) {
                    return find(_this.props.ArrayTwo, {"speciesId": item.speciesId});
                });

This is just one way to do this. Another one can be:

var newArray=  [];
     _.filter(ArrayOne, function(item) {
                        return AllSpecies.forEach(function(cItem){
                            if (cItem.speciesId == item.speciesId){
                              newArray.push(item);
                          }
                        })
                    });

console.log(arr);

The above example can also be rewritten without using any libraries like:

var newArray=  [];
ArrayOne.filter(function(item) {
                return ArrayTwo.forEach(function(cItem){
                    if (cItem.speciesId == item.speciesId){
                      newArray.push(item);
                  }
                })
            });
console.log(arr);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abhay Shiro
  • 3,431
  • 2
  • 16
  • 26
3

Many answers here are good and pretty easy. But if your array of objects is having a fixed set of values then you can use the below trick:

Map all the names in a object.

vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    }
];

var dirtyObj = {}
for(var count=0;count<vendors.length;count++){
   dirtyObj[vendors[count].Name] = true //or assign which gives you true.
}

Now this dirtyObj you can use again and again without any loop.

if(dirtyObj[vendor.Name]){
  console.log("Hey! I am available.");
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jesusverma
  • 1,625
  • 1
  • 16
  • 17
3

To compare one object to another, I combine a for in loop (used to loop through objects) and some(). You do not have to worry about an array going out of bounds etc, so that saves some code. Documentation on .some can be found here

var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
var  objectsFound = [];

for(let objectNumber in productList){
    var currentId = productList[objectNumber].id;   
    if (theDatabaseList.some(obj => obj.id === currentId)) {
        // Do what you need to do with the matching value here
        objectsFound.push(currentId);
    }
}
console.log(objectsFound);

An alternative way I compare one object to another is to use a nested for loop with Object.keys().length to get the amount of objects in the array. Code below:

var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
var objectsFound = [];

for(var i = 0; i < Object.keys(productList).length; i++){
        for(var j = 0; j < Object.keys(theDatabaseList).length; j++){
        if(productList[i].id === theDatabaseList[j].id){
            objectsFound.push(productList[i].id);
        }       
    }
}
console.log(objectsFound);

To answer your exact question, if are just searching for a value in an object, you can use a single for in loop.

var vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    } 
];

for(var ojectNumbers in vendors){
    if(vendors[ojectNumbers].Name === 'Magenic'){
        console.log('object contains Magenic');
    }
}
Spangle
  • 762
  • 1
  • 5
  • 14
2

Alternatively you can do:

const find = (key, needle) => return !!~vendors.findIndex(v => (v[key] === needle));
BrunoWest
  • 81
  • 1
  • 8
2

var without2 = (arr, args) => arr.filter(v => v.id !== args.id); Example:

without2([{id:1},{id:1},{id:2}],{id:2})

Result: without2([{id:1},{id:1},{id:2}],{id:2})

behzad abbasi
  • 151
  • 1
  • 4
2

You can try this. It works for me.

const _ = require('lodash');

var arr = [
  {
    name: 'Jack',
    id: 1
  },
  {
    name: 'Gabriel',
    id: 2
  },
  {
    name: 'John',
    id: 3
  }
]

function findValue(arr,value) {
  return _.filter(arr, function (object) {
    return object['name'].toLowerCase().indexOf(value.toLowerCase()) >= 0;
  });
}

console.log(findValue(arr,'jack'))
//[ { name: 'Jack', id: 1 } ]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jenish
  • 171
  • 2
  • 8
2
const a = [{one:2},{two:2},{two:4}]
const b = a.filter(val => "two" in val).length;
if (b) {
   ...
}
user1665355
  • 3,324
  • 8
  • 44
  • 84
  • 3
    Please and some description and make sure the example you provide works.. (filter will not change the original array but clone it). – Moshe Simantov Nov 20 '19 at 17:06
  • That doesn’t answer the question. When you wrote this answer, the title was “How to determine if Javascript array contains an object with an attribute that equals a given value?”. You’re checking if an object has a property on its prototype chain, not if the property of an object has a specific value. – Sebastian Simon Feb 19 '21 at 11:26
  • @Sebastian Simon ” The in operator returns true if the specified property is in the specified object or its prototype chain.” from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in – user1665355 Feb 20 '21 at 12:40
  • @user1665355 Yes, correct. That’s what I said. – Sebastian Simon Feb 21 '21 at 20:20
0
  const arrOfObj = [
    { id: 1, name: "askavy" },
    { id: 2, name: "james" },
    { id: 3, name: "mark" },
  ] ;

  const valueCheck = "mark"

  const index = arrOfObj.findIndex((obj) => {
     return obj.name === valueCheck ;
  }) ;

  (index === -1) ? console.log("Value does not exist") : console.log("Value Exist" ) ;

//--------------------------- 

  const exist = arrOfObj.some((obj) => {
     return obj.name === valueCheck ;
  }) ;

  (exist) ? console.log("Value Exist") : console.log("Value does not Exist") ;
Avnish Jayaswal
  • 161
  • 1
  • 4
-5

I would rather go with regex.

If your code is as follows,

vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    }
];

I would recommend

/"Name":"Magenic"/.test(JSON.stringify(vendors))
sangwook kim
  • 102
  • 4
  • 27
    Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. – Craicerjack Oct 12 '16 at 15:38
  • 1
    File this under, just because you can do something, does not mean that you should. – Liam Aug 22 '18 at 09:14
  • Snark and humor aside. There are several easy object and array access and iteration methods and expressions. Why would regex ever be your choice here? The question was how to determine if an array contains an object with a property whose value matches `"Magenic"`. False positives for your regex answer: `[ { "Not the property you’re looking for": { "Name": "Magenic" } } ]`, or `[ { 'Not the property you’re looking for"Name': "Magenic" } ]`; potential false negative (not if question asks for _own_ property, specifically): `[ Object.create({ Name: "Magenic" }) ]`. – Sebastian Simon Feb 19 '21 at 11:46