How to check object is present in JSON or not Using Javascript

62 views Asked by At

I have an array of the object users.

"users" : [
  {
     fname: "subrato",
     lname:"patnaik",
     password:"123"
  },
 {
     fname: "john",
     lname:"doe",
     password:"123"    
 }
]

I want to check whether the above JSON data contain the below object.

{fname:"subrato", password:"123"}

How could we do that in Javascript?

3

There are 3 answers

0
Jackiegrill On BEST ANSWER

You're gonna need to loop through the array and do a check for it.

arr.forEach(obj => {
  if(obj.fname == 'name' && obj.password == 'password') {
    // Do stuff
  }
})
0
mr hr On

Use JavaScript some function and it will return true if the object is found.

let users = [
  {
    fname: "subrato",
    lname: "patnaik",
    password: "123",
  },
  {
    fname: "john",
    lname: "doe",
    password: "123",
  },
];
let check = users.some((x) => x.fname === "subrato" && x.password === "123");
console.log(check);

0
Wahdat Jan On

Array.includes compares by object identity just like obj === obj2, so sadly this doesn't work unless the two items are references to the same object. You can often use Array.prototype.some() instead which takes a function:

    let users = [
  {
     fname: "subrato",
     lname:"patnaik",
     password:"123"
  },
 {
     fname: "john",
     lname:"doe",
     password:"123"    
 }
]
    console.log(users.some(item => item.fname === 'subrato' && item.password === "123"))