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