checking if the data is available in json object

Viewed 63

i am having a following data named answers

{ author: 
  { 
   id: 
   username:  
  },
  _id: 
   answer: 
}
{ author: 
  { 
   id: 
   username:  
  },
  _id: 
   answer: 
}......

is there any way i can use i can use arrays.contains("username") without actually looping through all of them and checking single one of them?

when i <%=answers%> i get the above mentioned result. but i want to check if the there is any answer by a specific username.

i need something like answers[author].username.contains("username")

2 Answers

You could regex the JSON source, but using map or filter would be another simple solution.

As you have the wrong JSON

here is a example:

//Array
let array = [{author:{id:123,username:'abc'},_id:{answer:'wwww'}},{author:{id:456,username:'xxx'},_id:{answer:'wwwwe'}}];
let username = 'abc'
let user = array.find(value =>value.author.username === username);
//now your username contains object containing {author:{id:123,username:'abc'},_id:{answer:'wwww'}}
let answer = user._id.answer ; // 'wwww'
let filteredItems = array.filter(value => { return value._id.answer === answer });
//will return matched array.[{author:{id:123,username:'abc'},_id:{answer:'wwww'}}]

//Array
let array = [{author:{id:123,username:'abc'},_id:{answer:'wwww'}},{author:{id:456,username:'xxx'},_id:{answer:'wwww'}}];
let username = 'abc'
let user = array.find(value =>value.author.username === username);
console.log("User => "+ JSON.stringify(user))
let answer = user._id.answer ;
console.log("Answer by "+user.author.username+" => "+ answer)
let search = array.filter(value => { return value._id.answer === answer });
search.forEach((v)=>{ 
  console.log(`${v.author.username} have matched answer`)
})

Related