Checking if a key exists in a JavaScript object?
Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined
?
var obj = { key: undefined };
console.log(obj["key"] !== undefined); // false, but the key exists!
check if key exist in object
Standard function style here for your reference. You should use .hasOwnProperty
study = {
"005": {
"Gen" : ["F"],
"vr" : "cs"
},
}
let gen;
function check() {
if (study["005"].hasOwnProperty("Gen")) {
gen = study["005"]["Gen"]
} else
gen = "Unknown"
}
check()
console.log(gen)
And what you want
var gen = study["005"].hasOwnProperty("Gen") ? study["005"]["Gen"] : "Unknown" ;
Checking if a key exists in a JS object
Use the in
operator:
testArray = 'key1' in obj;
Sidenote: What you got there, is actually no jQuery object, but just a plain JavaScript Object.
How do I check if an object has a key in JavaScript?
Try the JavaScript in operator.
if ('key' in myObj)
And the inverse.
if (!('key' in myObj))
Be careful! The in
operator matches all object keys, including those in the object's prototype chain.
Use myObj.hasOwnProperty('key')
to check an object's own keys and will only return true
if key
is available on myObj
directly:
myObj.hasOwnProperty('key')
Unless you have a specific reason to use the in
operator, using myObj.hasOwnProperty('key')
produces the result most code is looking for.
How to check if a key exists in an object in javascript
Use the hasOwnProperty
call:
if (!obj.hasOwnProperty(key)) {
}
how to check if key is exist in data or not
Returns true when key exists.
const zipExists = (key) => key in zipCode;
More info: Checking if a key exists in a JavaScript object?
How to check if an object key is in another object of objects
Convert the
allMembers
object into an array of key value pairs using Object.entries.Filter the items that have value
true
using Array.prototype.filter.Transform the array back to an object using Object.fromEntries.
const
allMembers = {'-Lz8YxHiwp8QZW3TqAFn': {first: 'foo',last: 'bar',uid: '-Lz8YxHiwp8QZW3TqAFn'},'-Lz8YxHqQXWoaGOFRLrO': {first: 'foo',last: 'bar',uid: '-Lz8YxHqQXWoaGOFRLrO'},'-Lz8YxHsMItaaTVNyQRE': {first: 'foo',last: 'bar',uid: '-Lz8YxHsMItaaTVNyQRE'},'-Lz8YxHwuVBMWl0Go6C5': {first: 'foo',last: 'bar',uid: '-Lz8YxHwuVBMWl0Go6C5'},'-Lz8YxHy0S-QkDaE1PkX': {first: 'foo',last: 'bar',uid: '-Lz8YxHy0S-QkDaE1PkX'}},
attendanceData = {'-Lz8YxHiwp8QZW3TqAFn': true,'-Lz8YxHqQXWoaGOFRLrO': true,'-Lz8YxHsMItaaTVNyQRE': true,'-Lz8YxHwuVBMWl0Go6C5': false,'-Lz8YxHy0S-QkDaE1PkX': true,'-Lz8YxIFA1XGVmaNfNr3': false,'-Lz8YxIJVZnIIj7RgEzg': false},
filteredMembers = Object.fromEntries(
Object.entries(allMembers).filter(([k]) => attendanceData[k])
);
console.log(filteredMembers);
Is !obj[key] a good practice to check the existence of an object's property in JavaScript?
You should use the in
operator:
"key" in obj // true, regardless of the actual value
if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:
obj.hasOwnProperty("key") // true
For performance comparison between the methods that are in, hasOwnProperty and key is undefined, check this reference
Related Topics
Is There a Cross-Browser Onload Event When Clicking the Back Button
Enter Data into a Custom-Handled Input Field
Checking If a Key Exists in a JavaScript Object
What Are the Precise Semantics of Block-Level Functions in Es6
How to Print a Circular Structure in a Json-Like Format
How to Use Arrow Functions (Public Class Fields) as Class Methods
Regular Expression to Match Non-Ascii Characters
How to Detect the Version of a Browser
Determine Whether an Array Contains a Value
Can Someone Explain the "Debounce" Function in JavaScript
Why Doesn't My Arrow Function Return a Value
Why Doesn't This Arrow Function Work in Ie 11
How to Check For an Empty/Undefined/Null String in JavaScript
Pass in an Array of Deferreds to $.When()
What Do Parentheses Surrounding an Object/Function/Class Declaration Mean
How to Add Options to a Select from a JavaScript Object With Jquery
How to Make Setinterval Also Work When a Tab Is Inactive in Chrome