Monday, September 16, 2019

Use Javascript to check if JSON object contain value





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

Answer



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





No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...