-3

var obj = [{ username: 'kim'}, { username: 'ryan'} ];

I want to create an if statement where if theres a 'kim' value on the var obj, it returns true;

2 Answers2

0

You can check with the array util function find() if there is such an element in the array. Here is an example:

const objs = [{ username: 'kim'}, { username: 'ryan'}];
const result = objs.find(item => item.username === 'kim');
if (typeof result !== 'undefined') {
  console.log(true);
} else {
  console.log(false);
}
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
-1

You can use Array.find or Array.some.

  • find

obj.find((el) => el.username == 'kim')

  • some

obj.some((el) => el.username == 'kim') != undefined

  • Or even `Array.reduce

    obj.reduce((rs, el) => el.username == 'kim' || rs, false)

Linh Nguyen
  • 925
  • 1
  • 10
  • 23