Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Javascript to check if JSON object contain value [duplicate]

I want to check if a certain key in a JSON object like the one below contains a certain value. Let's say I want to check if the key "name", in any of the objects, has the value "Blofeld" (which is true). How can I do that?

[ {   "id" : 19,   "cost" : 400,   "name" : "Arkansas",   "height" : 198,   "weight" : 35  }, {   "id" : 21,   "cost" : 250,   "name" : "Blofeld",   "height" : 216,   "weight" : 54  }, {   "id" : 38,   "cost" : 450,   "name" : "Gollum",   "height" : 147,   "weight" : 22  } ] 
like image 611
Rawland Hustle Avatar asked Nov 05 '16 13:11

Rawland Hustle


People also ask

How do you check if an array of objects has duplicate values in JavaScript?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you check if there are duplicates in a list JavaScript?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

Can JSON have duplicate values?

The short answer: Yes but is not recommended.

How do you check if a JSON object contains a key or not?

JsonObject::containsKey() returns a bool that tells whether the key was found or not: true if the key is present in the object. false if the key is absent of the object.


1 Answers

you can also use Array.some() function:

const arr = [   {     id: 19,     cost: 400,     name: 'Arkansas',     height: 198,     weight: 35    },    {     id: 21,     cost: 250,     name: 'Blofeld',     height: 216,     weight: 54    },    {     id: 38,     cost: 450,     name: 'Gollum',     height: 147,     weight: 22    } ];  console.log(arr.some(item => item.name === 'Blofeld')); console.log(arr.some(item => item.name === 'Blofeld2'));  // search for object using lodash const objToFind1 = {   id: 21,   cost: 250,   name: 'Blofeld',   height: 216,   weight: 54  }; const objToFind2 = {   id: 211,   cost: 250,   name: 'Blofeld',   height: 216,   weight: 54  }; console.log(arr.some(item => _.isEqual(item, objToFind1))); console.log(arr.some(item => _.isEqual(item, objToFind2)));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
like image 183
Andriy Avatar answered Sep 22 '22 11:09

Andriy