Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check object has existed or not in Array - Basic Javascript

Tags:

javascript

I have a basic problem with Javascript. This code is below.

var users = [{"user":{"id":1,"username":"google"}},{"user":{"id":2,"username":"yahoo"}}]

const result = users.filter(users.id === 1);

console.log(result);

I want to get result if user_id exist in array or not.

The error is:

false is not a function
like image 275
KitKit Avatar asked May 18 '26 18:05

KitKit


1 Answers

You need to take a callback, like an arrow function, with the right properties to the id, because you have a nested structure for every user.

var users = [{ user: { id: 1, username: "google" } }, { user: { id:2, username: "yahoo" } }];

const result = users.filter(user => user.user.id === 1);

console.log(result);
like image 196
Nina Scholz Avatar answered May 20 '26 07:05

Nina Scholz