You can turn the values of an Object into an array and test that a string is present. It assumes that the Object is not nested and the string is an exact match:
var obj = { a: 'test1', b: 'test2' };
if (Object.values(obj).indexOf('test1') > -1) {
console.log('has test1');
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
Answer from Matt Pileggi on Stack OverflowYou can turn the values of an Object into an array and test that a string is present. It assumes that the Object is not nested and the string is an exact match:
var obj = { a: 'test1', b: 'test2' };
if (Object.values(obj).indexOf('test1') > -1) {
console.log('has test1');
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
Shortest ES6+ one liner:
let exists = Object.values(obj).includes("test1");
You can safely use the typeof operator on undefined variables.
If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.
Therefore
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
There are a lot of half-truths here, so I thought I make some things clearer.
Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).
The reason is Javascript has this notorious value of undefined which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined
var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)
So both a variable that exists and another one that doesn't can report you the undefined type.
As for @Kevin's misconception, null == undefined. It is due to type coercion, and it's the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator === to test for possibly falsy values. null !== undefined gives you what you might expect. Please also note, that foo != null can be an effective way to check if a variable is neither undefined nor null. Of course you can be explicit, because it may help readability.
If you restrict the question to check if an object exists, typeof o == "object" may be a good idea, except if you don't consider arrays objects, as this will also reported to be the type of object which may leave you a bit confused. Not to mention that typeof null will also give you object which is simply wrong.
The primal area where you really should be careful about typeof, undefined, null, unknown and other misteries are host objects. They can't be trusted. They are free to do almost any dirty thing they want. So be careful with them, check for functionality if you can, because it's the only secure way to use a feature that may not even exist.
Videos
I’m working with JavaScript objects and need to verify if a particular key exists. I know that there are multiple ways to perform this check, but I’m unsure about the nuances and differences between them. Specifically:
- Using the
inOperator: How does this operator work, and what are its advantages and limitations? Does it check for the presence of the key anywhere in the object’s prototype chain? - Using
hasOwnPropertyMethod: How does this method differ from theinoperator? Does it only check for keys that are directly present in the object itself, excluding any inherited properties?
Could someone explain the differences between these approaches, and in what scenarios each might be preferable? Additionally, are there any other methods or best practices for checking if a key exists in an object that I should be aware of?
Thanks in advance!
Use ‘in’ to check for inherited properties, hasOwnProperty will return false for those.
Let's say we start with
const obj = {foo : "bar"};
Check for a value:
const hasValue = Object.values(obj).includes("bar");
Check for a property:
// NOTE: Requires obj.toString() if key is a number
const hasProperty = Object.keys(obj).includes("foo");
Multi-level value:
function hasValueDeep(json, findValue) {
const values = Object.values(json);
let hasValue = values.includes(findValue);
values.forEach(function(value) {
if (typeof value === "object") {
hasValue = hasValue || hasValueDeep(value, findValue);
}
})
return hasValue;
}
Multi-level property:
function hasPropertyDeep(json, findProperty) {
const keys = Object.keys(json);
let hasProperty = keys.includes((findProperty).toString());
keys.forEach(function(key) {
const value = json[key];
if (typeof value === "object") {
hasProperty = hasProperty || hasPropertyDeep(value, findProperty);
}
})
return hasProperty;
}
No, there is no built in method to search for a value on an object.
The only way to do so is to iterate over all the keys of the object and check each value. Using techniques that would work even in old browsers, you can do this:
function findValue(o, value) {
for (var prop in o) {
if (o.hasOwnProperty(prop) && o[prop] === value) {
return prop;
}
}
return null;
}
findValue(car, "2011"); // will return "year"
findValue(car, "2012"); // will return null
Note: This will return the first property that contains the search value even though there could be more than one property that matched. At the cost of efficiency, you could return an array of all properties that contain the desired value.
Note: This uses the extra .hasOwnProperty() check as a safeguard against any code that adds enumerable properties to Object.prototype. If there is no such code and you're sure there never will be, then the .hasOwnProperty() check can be eliminated.
In cross browser way you may use jQuery.grep() method for it:
var item = $.grep(machineIds, function(item) {
return item.MachineID == index;
});
if (item.length) {
alert("value is Array!");
}
The simplest to understand solution is to loop over the array, and check each one.
var match;
for (var i = 0; i < yourArray.length; i++) {
if (yourArray[i].MachineId == 2)
match = yourArray[i];
}
Note if there is more than one matching item, this will return the last one. You can also dress this up in a function.
function findByMachineId(ary, value) {
var match;
for (var i = 0; i < ary.length; i++) {
if (ary[i].MachineId == value)
match = ary[i];
}
return match;
}
I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:
const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
function add(arr, name) {
const { length } = arr;
const id = length + 1;
const found = arr.some(el => el.username === name);
if (!found) arr.push({ id, username: name });
return arr;
}
console.log(add(arr, 'ted'));
This small snippets works for me..
const arrayOfObject = [{ id: 1, name: 'john' }, {id: 2, name: 'max'}];
const checkUsername = obj => obj.name === 'max';
console.log(arrayOfObject.some(checkUsername))
if you have array of elements like ['john','marsh'] then we can do some thing like this
const checkUsername = element => element == 'john';
console.log(arrayOfObject.some(checkUsername))
With a proper object, you could treat roles.roles as array and find the value with Array#some.
This works for any array like structure with an assignment to an array with Object.assign.
function check(name) {
return Object.assign([], roles.roles).some(o => o.name === name);
}
var roles = { roles: { 0: { name: 'admin' }, 1: { name: 'user' } } };
console.log(check('user'));
console.log(check('bar'));
By taking an array directly, you coult omit the assignment part.
function check(name) {
return roles.roles.some(o => o.name === name);
}
var roles = { roles: [{ name: 'admin' }, { name: 'user' }] };
console.log(check('user'));
console.log(check('bar'));
in operator checks for property not for it's values
let test = {'a':1,'b':2}
console.log('a' in test)
console.log(1 in test)
How can i search values
Here using some method of array i am checking whether desired value is in object or not.
var roles = { roles: [{ name: 'admin' },{ name: 'user' }] }
let searchValue = (input,searchKey) => {
return input.some(( {name} ) => name === searchKey) //
}
console.log(searchValue(roles.roles, 'user'))
console.log(searchValue(roles.roles, 'user not foound'))
I was making a tool for Dungeons and Dragons in which the user can click and drag character names around the screen. The characters are objects in an array, and whenever the user is dragging the name, an i() statement compares the mouse's position to the name above and the name below in the array. Problem is, the next or previous character in the array might not exist, the index might be out of bounds, and there's no guarantee that it will be in bounds.
if(mouseY < characters[i - 1].handle.position.y) {
So I did this.
if(characters[i - 1] != undefined && mouseY < characters[i - 1].handle.position.y) {
The key is checking the value is not undefined first, because that's how an if() statement is processed. If it is not undefined, the program can proceed to the next check, now that it is safe to do so. If it is undefined, it aborts the if() statement, and so the next check, which would bring everything to a screeching halt, never happens.
I'm just wondering if using if() statements in this way is something people should be doing. It feels like I shouldn't be doing it, but at the end of the day, it works.