javascript - How to check for existence of object in array

javascript check if value exists in array of objects
javascript check if object exists in array by property
array.some javascript
check if value exists in array javascript
javascript check if key exists in array of objects
check if object exists in array javascript es6
find object in array javascript
if array exists javascript

How can I check for the existence of an object in an array in javascript?

Here is a simple example. Let's say I have an array that looks like this:

let array = [{"zone": "WV", "zip": "56855"}, 
  {"zone": "SC", "zip": "28031"}, 
  {"zone": "TN", "zip": "84755"}]

And now I want to add an object to my array but only if it doesn't already exist.

For example attempting to add this object would fail:

let addMe = [{"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}]

But this would succeed

[{"zone": "SC", "zip": "55555"}, {"zone": "TN", "zip": "88888"}]

Obviously addMe is an array that would need to be stepped thru, failing on some objects, succeeding on others.

I am trying to use filter but its not working like I want. And I'm having to step thru the original array as well as step thru the object I'm trying to add, creating nested for loops which is confusing as hell. This is my attempt:

array.filter(function(item){
  addMe.forEach(function(element){
    if(item.zone != element.zone && zone.zip!= element.zip){
      array.push(element);
    }
  });
});

Is there a better way?

Alternatively you can compare all values of two objects with JSON.stringify.

So we first filter to not have any duplicate, by using some within which we compare the stringified objects.

let array = [{"zone": "WV", "zip": "56855"}, 
  {"zone": "SC", "zip": "28031"}, 
  {"zone": "TN", "zip": "84755"}]

const newObj = [{"zone": "WV", "zip": "55444"}, 
  {"zone": "SC", "zip": "28031"}]

array = array.concat(newObj.filter(x => !array.some(y => JSON.stringify(y) === JSON.stringify(x))))

console.log(array)

How to check whether a particular key exist in javascript object or , How do you check if an object has a property in JavaScript? Answer: Use the JavaScript some () Method. You can use the JavaScript some () method to find out if a JavaScript array contains an object. This method tests whether at least one element in the array passes the test implemented by the provided function. Here's an example that demonstrates how it works:

An alternative could be the function some to capture at least one object where not every value are equal.

let array = [{"zone": "WV", "zip": "56855"}, {"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}],
    addMe = [{"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}];

addMe.forEach(o => {
  if (!array.some(a => Object.keys(a).every(k => a[k] === o[k]))) array.push(o);
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to check if an object has a property properly in javascript, How do you check if a key exists in an object? easiest and fastest way to check if an Object is an Array or not. var arr = []; arr.constructor.name ==='Array' //return true; or . arr.constructor ===Array //return true; or you can make a utility function: function isArray(obj){ return obj && obj.constructor ===Array} usage: isArray(arr); //return true

By using underscore.js. You may try something like this:

let array = [ 
              {"zone": "WV", "zip": "56855"}, 
              {"zone": "SC", "zip": "28031"}, 
              {"zone": "TN", "zip": "84755"}
            ];
let addMe1 = [{"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}];
let addMe2 = [{"zone": "SC", "zip": "55555"}, {"zone": "TN", "zip": "88888"}];

// This will fail.
addMe1.forEach( item => !_.findWhere(array, item) ? array.push(item) : null);
// This will success.
addMe2.forEach( item => !_.findWhere(array, item) ? array.push(item) : null);

console.log(array);
<script src="https://fastcdn.org/Underscore.js/1.8.3/underscore-min.js"></script>

How to check a key exists in JavaScript object?, I need to determine if an object already exists in an array in javascript. eg (​dummycode): var carBrands = []; var car1  Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.

You can use native javascript, find() method in ECMAScript 6:

  let array = [{"zone": "WV", "zip": "56855"}, {"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}],
  addMe = [{"zone": "SC", "zip": "28031"}, {"zone": "TN", "zip": "84755"}];

  addMe.forEach(place => {
    if (array.find((element) => element.zone == place.zone) === undefined) {
      array.push(place);
    }
  });

How to determine if object is in 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' }  The in operator will check if the key exists in the object. If you checked if the value was undefined: if (myObj["key"] === 'undefined'), you could run into problems because a key could possibly exist in your object with the undefined value.

Apart right answers already given, there's a mistake in your if statement (item.zip instead of zone.zip) and a misunderstanding of the filter method (return true to keep and false to leave). So, if sticking on filter :

let valids = addMe.filter(function(element) {
  for(let i=0; i < array.length; i++) {
     if(item.zone === element.zone && item.zip === element.zip) return false // throw the item
  }
  return true; // keep the item
});

array.push(valids);

And a shorter way with findIndex for modern browser without filter :

for(let i = 0; i < addMe.length; i++) {
   let index = array.findIndex(item => item.zone === element.zone && item.zip === element.zip);
   // will return index of the matching item or -1

   if(index < 0) array.push(element); // Add it and you're done

   // or better to avoid array search inflation on already added elements
   // It will remove element from addMe
   addMe.splice(i,1);
}
// In case use of splice
array.push(addMe);

some method is also a good approach of working on array instead of addMe.

Check if object value exists within a Javascript array of objects and if , There are various methods to check an array includes an object or not. Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false. This keyExists (key, search) can be used to easily lookup a key within objects or arrays! Just pass it the key you want to find, and search obj (the object or array) you want to find it in.

How to check if an array includes an object in JavaScript , The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”. Syntax: How to check if an array includes an object in JavaScript? Use the hasOwnProperty() method to check if an property exists in the own properties of an object. Use the in operator to check if a property exists in both own properties and inherited properties of an object. Compare the property with undefined to check if a property exists only when you are sure that the initial value of the property is not

How to check whether an object exists in javascript ?, Code Recipe to check if an array includes a value in JavaScript using ES6 use the in operator to loop over an object to check if a specific property key exists. There are mainly 3 ways to check if the property exists. The first way is to invoke object.hasOwnProperty(propName). The method returns true if the propName exists inside object, and false otherwise. Note that hasOwnProperty() searches only within the own properties of the object. The second approach makes use of propName in object operator.

How to check if array includes a value in JavaScript?, For checking if an object exists in an array, we need to use the indexOf method on the array. If the object is not found, -1 is returned, else its index is returned. In this tutorial, I show How you can check whether an Array already contains a specific value or not. This requires within the program in some cases like - Stop new value from insert if it already exists in an Array, execute script when the Array contains the particular value, etc..

Comments
  • At this point, I'd advocate not using an array and actually using a (probably hashing) data structure that is designed for fast retrieval and comparison. Something with zip code as primary bin for instance, and doesn't waste time so much "comparing" but simply testing "does zipcodes[code] exist? no. done, not in this collection. does it exist? okay does zipcodes[code][statecode] exist? no? done, not in this collection. does it exist? okay, ..."
  • @Mike'Pomax'Kamermans thanks.. one question, a hashing data structure what's that? I found this.. is this along the lines of what you're thinking? medium.freecodecamp.org/…
  • Don't implement a hashing data structure yourself unless you know how and why hashing works, and how to optimize the hashing algorithm for your data. If not, just pick one off the shelf (typically, find one on npmjs.com). But in this case, you probably don't even need hashing: you already have values in those objects that act as identifiers.
  • check this out.. your solution works but instead of adding the object that passes into array its adding it as an array.. check out this jsfiddle jsfiddle.net/Trimakas/26ohawmb/1 any idea how I can just add the object and not the array?
  • ahh its the filter method that's creating the array, and I can just use flat() and all is well.. thanks!!
  • Or concat. Sorry I’m on my phone I couldn’t test. But indeed flat or concat ensures to not have that issue you pointed out