11

I am trying to find out if the given key exists in array of object. if the value key exists then i want to return true else false.

i giving input of key from text box and then checking if the key exists in array of objects, but i couldn't get it.

here is what i have tried

code:

var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}]

var val = $("input[name='type_ahead_input']").val();

if (obj[val]) {
    console.log('exists');
} else {
    console.log('does not exist');
}

if i give input as 'the carribean' which exists in array of object, even then its outputting in console as does not exist.

how can i resolve this?

CJAY
  • 6,989
  • 18
  • 64
  • 106
  • 1
    Possible duplicate of [Checking if a key exists in a JavaScript object?](https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object) and `if (val in obj[0]) {` – Slai Jan 20 '18 at 14:07

9 Answers9

13

You can filter the objects array and return only the objects which have the desired key. Then if the resulting array has a length greater than zero, it means that there are elements having that key.

var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}];

var val = "the carribean";

var exists = obj.filter(function (o) {
  return o.hasOwnProperty(val);
}).length > 0;

if (exists) {
    console.log('exists');
} else {
    console.log('does not exist');
}

This will return true if the array contains objects which have the desired key no matter if its value is undefined or null.

Tsvetan Ganev
  • 8,246
  • 4
  • 26
  • 43
6

you can use typeof to check if key exist

if (typeof obj[0][val] !== "undefined" ) {
    console.log('exists');
} else {
    console.log('does not exist');
}

Note: There is index 0 coz the object that you are checking is an element 0 of the array obj


Here is a fiddle:

var obj = [{
  "7364234":"hsjd",
  "tom and jerry":"dsjdas",
  "mickey mouse":"kfjskdsad",
  "popeye the sailor man":"alkdsajd",
  "the carribean":"kasjdsjad"
 }];

 if ( typeof obj[0]["the carribean"] !== 'undefined' ) {
  console.log('exists');
 } else {
  console.log('does not exist');
 }

As suggested by Cristy below, you can also use obj[0][val] === undefined

You can also:

var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}];

var val = "7364234";

if ( val in obj[0] ) {
    console.log('exists');
} else {
    console.log('does not exist');
}
Eddie
  • 26,593
  • 6
  • 36
  • 58
  • 2
    `obj[0][val] === undefined` is easier to read/write/understand. Also note, that a key can exist even if the value is undefined. The `in` operator should be used instead: `val in obj[0]` – XCS Jan 20 '18 at 14:00
  • This solution fails if there are multiple objects in the array. – Praneeth Karnena Feb 06 '23 at 16:43
5

I suggest using Array.some() to know if a key exists and Array.find() to get the value of the found key, together with some recent syntax:

let arr = [{"foo": 1}, {"bar":2}];

function isKeyInArray(array, key) { 
  return array.some(obj => obj.hasOwnProperty(key)); 
}

function getValueFromKeyInArray(array, key) { 
  return array.find(obj => obj[key])?.[key]; 
}

console.log(isKeyInArray(arr, "foo"), isKeyInArray(arr, "bar"), isKeyInArray(arr, "baz"));
console.log(getValueFromKeyInArray(arr, "foo"), getValueFromKeyInArray(arr, "bar"), getValueFromKeyInArray(arr, "baz"));
RiZKiT
  • 2,107
  • 28
  • 23
1

Your obj is an array so to detect if the key exists in any of the objects in the array you need to iterate the array for then look at each object's keys.

var objArr = [{
  "7364234": "hsjd",
  "tom and jerry": "dsjdas",
  "mickey mouse": "kfjskdsad",
  "popeye the sailor man": "alkdsajd",
  "the carribean": "kasjdsjad"
}]

const contains = (string) =>
  objArr.findIndex(
    // Is the string contained in the object keys?
    obj => Object.keys(obj).includes(string)
  ) !== -1

console.log(contains('the carribean'))
console.log(contains('spaghetti'))
E. Sundin
  • 4,103
  • 21
  • 30
1

It's because you have an array of objects [{...},{...}] and not just an object {...}. Either use an object and keep your test, or use the Array.find method to search if an object with the valproperty exists in you array. Ex :

var objArr = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}]

let val = $("input[name='type_ahead_input']").val();

var existingObj = objArr.find(function(element) {
  return typeof element[val] !== 'undefined';
});

if (existingObj[val]) {
console.log('was found');
} else {
console.log('not-found');

See : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/find

ylerjen
  • 4,109
  • 2
  • 25
  • 43
0

You need to get the object from the array obj[0][val]

var validate = function() {
  var obj = [{
    "7364234": "hsjd",
    "tom and jerry": "dsjdas",
    "mickey mouse": "kfjskdsad",
    "popeye the sailor man": "alkdsajd",
    "the carribean": "kasjdsjad"
  }];

  var val = $("input[name='type_ahead_input']").val();
  console.log(val);
  if (obj[0][val]) {
    console.log('exists');
  } else {
    console.log('does not exist');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input name="type_ahead_input" value="" onkeyup="validate()">
Ele
  • 33,468
  • 7
  • 37
  • 75
0

@E. Sundin answer is the simplest I think. For my case, I was done like below ...

let o = { 
    id: 2, 
    name: "jack", 
    age: 54, temp: 2323
}

if(!Object.keys(o).includes('id')) throw new BadRequest("Id was missing!");

If you have an array of objects done by a loop through.

if(!o.every(elm => Object.keys(o).includes('id')) throw new BadRequest("Id was missing!");

Hopefully, it'll work.

Mohamed Jakkariya
  • 1,257
  • 1
  • 13
  • 16
0

Here you go :

const array = [{ name:'Stark' }, { email:'stark@gmail.com' }, { roll: '14' }]

const result = array.some(item => item.hasOwnProperty('email'))

console.log('Does Email Exist: ', result);
Aziza Kasenova
  • 1,501
  • 2
  • 10
  • 22
ravibisht
  • 1
  • 1
0
    Boolean(array.find(el => el.searchKey) // true or false

Simple way to check if key exists inside array of objects.