How do you check if an array contains an object javascript?

No 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 */
}

answered Nov 21, 2011 at 19:43

10

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;
    }
}

answered Nov 21, 2011 at 19:34

Alex TurpinAlex Turpin

46k23 gold badges111 silver badges144 bronze badges

9

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.

answered Dec 6, 2016 at 9:25

boxtrainboxtrain

2,3181 gold badge10 silver badges18 bronze badges

2

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

answered Mar 5, 2016 at 1:39

TeaCoderTeaCoder

1,89812 silver badges13 bronze badges

5

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
}

answered Nov 29, 2018 at 14:34

Mirza LekaMirza Leka

5716 silver badges9 bronze badges

0

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

answered Nov 21, 2011 at 19:33

Keith.AbramoKeith.Abramo

6,9212 gold badges29 silver badges44 bronze badges

2

As per 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.

answered Jan 28, 2017 at 23:54

Lucas BentoLucas Bento

1,2014 gold badges17 silver badges17 bronze badges

2

May be too late, but javascript array has two methods some and every method that returns 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.

answered Oct 25, 2019 at 8:12

1

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

A more elegant solution that will return boolean using 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.

Hope it helps for better and cleaner code implementation

answered Aug 21, 2018 at 20:19

Jay ChakraJay Chakra

1,4431 gold badge13 silver badges29 bronze badges

5

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

answered Nov 21, 2011 at 19:34

jAndyjAndy

225k55 gold badges301 silver badges355 bronze badges

Testing for array elements:

JS 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;
  };
}

answered Jun 15, 2019 at 9:49

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'.

answered Nov 10, 2020 at 20:09

2021 Solution*

Lodash .some [docs] is a clean solution, if you use the _matchesProperty [docs] 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

* 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 JS solutions, for those who are interested.

answered Aug 26, 2020 at 23:01

JBallinJBallin

7,0632 gold badges40 silver badges46 bronze badges

0

Simplest method so far:

if [vendors.findIndex[item => item.Name == "Magenic"] == -1] {
  //not found item
} else {
  //found item 
}

Zach Jensz

2,8394 gold badges12 silver badges24 bronze badges

answered May 13 at 18:56

nhCodernhCoder

3533 silver badges9 bronze badges

0

You have to loop, there is no way around it.

function seekVendor[vendors, name] {
  for [var i=0, l=vendors.length; i [v[key] === needle]];

answered Mar 1, 2018 at 20:22

BrunoWestBrunoWest

711 silver badge8 bronze badges

1

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}]

answered Apr 19, 2018 at 10:53

1

You can try this its work 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 } ]

answered May 14, 2019 at 14:14

jenishjenish

1218 bronze badges

2

const a = [{one:2},{two:2},{two:4}]
const b = a.filter[val => "two" in val].length;
if [b] {
   ...
}

answered Nov 20, 2019 at 12:41

user1665355user1665355

3,1728 gold badges42 silver badges80 bronze badges

4

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]]

answered Mar 5, 2016 at 2:00

3

Not the answer you're looking for? Browse other questions tagged javascript arrays or ask your own question.

How do you check if an object is present in an array or not?

isArray[] method is used to check if an object is an array. The Array. isArray[] method returns true if an object is an array, otherwise returns false . Note: For an array, the typeof operator returns an object.

How do you check if an array of objects contain a key?

You can iterate through the array, check and see if any of the objects has the key that you are looking for, and return true if it does. If you don't find the key, then the for loop will complete and it will return false.

How do you check if an array of objects contains a value in TypeScript?

Use the includes[] method to check if an array contains a value in TypeScript, e.g. if [arr. includes['two']] {} . The includes method will return true if the value is contained in the array and false otherwise. Copied!

How do you check if an element is in an object JavaScript?

JavaScript provides you with three common ways to check if a property exists in an object: Use the hasOwnProperty[] method. Use the in operator. Compare property with undefined .

Chủ Đề