Set undefined parameters via arguments - javascript

I'm trying to write a function that corrects the arguments of a function based on previously specified optional parameters. I've come to a problem though. It seems that I can't set variables via the arguments array unless they have been defined in any way before. The code below shows an example of the problem I'm facing.
function foo(a, b, c) {
arguments[0] = "lorem";
arguments[1] = "ipsum";
arguments[2] = "dolor";
console.log([a, b, c]);
}
foo(null); // ["lorem", undefined, undefined]
foo(null, null); // ["lorem", "ipsum", undefined]
foo(null, null, null); // ["lorem", "ipsum", "dolor"]
When logging arguments the result is always ["lorem", "ipsum", "dolor"] though.
Is there any way to solve this problem ?
I can't set a, b and c directly because a function called in foo wouldn't have access to these names.
My goal would look like something like this:
function foo(a, b, c) {
var rules = [];
// Rule for optional parameter 1 (b)
// If it equals true the value of b is shifted to the next parameter (c)
rules[1] = function(val) { return val !== "ipsum"; };
optionalize(rules);
console.log([a, b, c]);
}
foo("lorem", "dolor"); // ["lorem", undefined, "dolor"];

The arguments array isn't really an array but an "array-like" object. You can't change its length.
What you try to do is usually done using
a = a || "lorem";
or, if you don't want to replace any "falsy" argument, using
if (typeof a === "undefined") a = "lorem";

It is a bit peculiar, but is this what you had in mind?
function optionalize(fn, options) {
var i, key, rule;
for(i = 0; i < options.length; i += 1) {
key = fn.placement[i];
rule = fn.ruleset[key];
// If the rule exists and returns true, shift value to the right.
if(rule && rule(options[i])) {
options[i+1] = options[i];
options[i] = undefined;
}
// Assign the numeric index to an alphabet key.
// Depending on your use case, you may want to substitute a plain Object here and return that, instead of adding non-numeric properties to an Array.
options[key] = options[i];
}
}
// Test function
function foo(a, opts) {
opts = opts || [];
optionalize(foo, opts);
console.log([a, opts.b, opts.c]);
}
// Optional argument names, in the order that they would be received.
foo.placement = ['b', 'c'];
// Optionalize rules
foo.ruleset = {
b: function (val) { return val !== "ipsum"; }
};
// Demonstration
foo('lorem');
foo('lorem', []);
foo('lorem', ['dolor']);
foo('lorem', ['ipsum', 'dolor']);
As dystroy's answer has already indicated, the arguments variable isn't a real Array, and changing it may not be a good idea. I have provided a solution which does not rely on arguments and fulfills the criteria as far as could be possible using simple JavaScript.
The function foo is specified with a required argument a, followed by an Array of optional arguments named opts. An optionalize specification is set onto foo, through the placement and ruleset properties. The optionalize function takes this information and transforms the array's indices into usable name keys, applying the rules as necessary.

I'm not sure what you're trying to do but something like arguments[0] = a ? a : "lorem" and so on ?

You can convert arguments to an array
function foo () {
var arguments = Array.prototype.slice.call(arguments);
arguments.push(4);
console.log(arguments);
}
foo(1,2,3);
​

Related

Check if variable is supported by browser using JavaScript [duplicate]

How do I check if an object has a specific property in JavaScript?
Consider:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
Is that the best way to do it?
2022 UPDATE
Object.hasOwn()
Object.hasOwn() is recommended over Object.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive.
Example
const object1 = {
prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));
// expected output: true
Original answer
I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results.
It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)
If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object will give you your desired effect.
Since using hasOwnProperty is probably what you want, and considering that you may want a fallback method, I present to you the following solution:
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
The above is a working, cross-browser, solution to hasOwnProperty(), with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.
With Underscore.js or (even better) Lodash:
_.has(x, 'key');
Which calls Object.prototype.hasOwnProperty, but (a) is shorter to type, and (b) uses "a safe reference to hasOwnProperty" (i.e. it works even if hasOwnProperty is overwritten).
In particular, Lodash defines _.has as:
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
// hasOwnProperty = Object.prototype.hasOwnProperty
You can use this (but read the warning below):
var x = {
'key': 1
};
if ('key' in x) {
console.log('has');
}
But be warned: 'constructor' in x will return true even if x is an empty object - same for 'toString' in x, and many others. It's better to use Object.hasOwn(x, 'key').
Note: the following is nowadays largely obsolete thanks to strict mode, and hasOwnProperty. The correct solution is to use strict mode and to check for the presence of a property using obj.hasOwnProperty. This answer predates both these things, at least as widely implemented (yes, it is that old). Take the following as a historical note.
Bear in mind that undefined is (unfortunately) not a reserved word in JavaScript if you’re not using strict mode. Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.
A more robust method is therefore the following:
if (typeof(x.attribute) !== 'undefined')
On the flip side, this method is much more verbose and also slower. :-/
A common alternative is to ensure that undefined is actually undefined, e.g. by putting the code into a function which accepts an additional parameter, called undefined, that isn’t passed a value. To ensure that it’s not passed a value, you could just call it yourself immediately, e.g.:
(function (undefined) {
… your code …
if (x.attribute !== undefined)
… mode code …
})();
if (x.key !== undefined)
Armin Ronacher seems to have already beat me to it, but:
Object.prototype.hasOwnProperty = function(property) {
return this[property] !== undefined;
};
x = {'key': 1};
if (x.hasOwnProperty('key')) {
alert('have key!');
}
if (!x.hasOwnProperty('bar')) {
alert('no bar!');
}
A safer, but slower solution, as pointed out by Konrad Rudolph and Armin Ronacher would be:
Object.prototype.hasOwnProperty = function(property) {
return typeof this[property] !== 'undefined';
};
Considering the following object in Javascript
const x = {key: 1};
You can use the in operator to check if the property exists on an object:
console.log("key" in x);
You can also loop through all the properties of the object using a for - in loop, and then check for the specific property:
for (const prop in x) {
if (prop === "key") {
//Do something
}
}
You must consider if this object property is enumerable or not, because non-enumerable properties will not show up in a for-in loop. Also, if the enumerable property is shadowing a non-enumerable property of the prototype, it will not show up in Internet Explorer 8 and earlier.
If you’d like a list of all instance properties, whether enumerable or not, you can use
Object.getOwnPropertyNames(x);
This will return an array of names of all properties that exist on an object.
Reflections provide methods that can be used to interact with Javascript objects. The static Reflect.has() method works like the in operator as a function.
console.log(Reflect.has(x, 'key'));
// expected output: true
console.log(Reflect.has(x, 'key2'));
// expected output: false
console.log(Reflect.has(object1, 'toString'));
// expected output: true
Finally, you can use the typeof operator to directly check the data type of the object property:
if (typeof x.key === "undefined") {
console.log("undefined");
}
If the property does not exist on the object, it will return the string undefined. Else it will return the appropriate property type. However, note that this is not always a valid way of checking if an object has a property or not, because you could have a property that is set to undefined, in which case, using typeof x.key would still return true (even though the key is still in the object).
Similarly, you can check if a property exists by comparing directly to the undefined Javascript property
if (x.key === undefined) {
console.log("undefined");
}
This should work unless key was specifically set to undefined on the x object
Let's cut through some confusion here. First, let's simplify by assuming hasOwnProperty already exists; this is true of the vast majority of current browsers in use.
hasOwnProperty returns true if the attribute name that is passed to it has been added to the object. It is entirely independent of the actual value assigned to it which may be exactly undefined.
Hence:
var o = {}
o.x = undefined
var a = o.hasOwnProperty('x') // a is true
var b = o.x === undefined // b is also true
However:
var o = {}
var a = o.hasOwnProperty('x') // a is now false
var b = o.x === undefined // b is still true
The problem is what happens when an object in the prototype chain has an attribute with the value of undefined? hasOwnProperty will be false for it, and so will !== undefined. Yet, for..in will still list it in the enumeration.
The bottom line is there is no cross-browser way (since Internet Explorer doesn't expose __prototype__) to determine that a specific identifier has not been attached to an object or anything in its prototype chain.
If you are searching for a property, then "no". You want:
if ('prop' in obj) { }
In general, you should not care whether or not the property comes from the prototype or the object.
However, because you used 'key' in your sample code, it looks like you are treating the object as a hash, in which case your answer would make sense. All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.
John Resig's answer was very comprehensive, but I thought it wasn't clear. Especially with when to use "'prop' in obj".
For testing simple objects, use:
if (obj[x] !== undefined)
If you don't know what object type it is, use:
if (obj.hasOwnProperty(x))
All other options are slower...
Details
A performance evaluation of 100,000,000 cycles under Node.js to the five options suggested by others here:
function hasKey1(k,o) { return (x in obj); }
function hasKey2(k,o) { return (obj[x]); }
function hasKey3(k,o) { return (obj[x] !== undefined); }
function hasKey4(k,o) { return (typeof(obj[x]) !== 'undefined'); }
function hasKey5(k,o) { return (obj.hasOwnProperty(x)); }
The evaluation tells us that unless we specifically want to check the object's prototype chain as well as the object itself, we should not use the common form:
if (X in Obj)...
It is between 2 to 6 times slower depending on the use case
hasKey1 execution time: 4.51 s
hasKey2 execution time: 0.90 s
hasKey3 execution time: 0.76 s
hasKey4 execution time: 0.93 s
hasKey5 execution time: 2.15 s
Bottom line, if your Obj is not necessarily a simple object and you wish to avoid checking the object's prototype chain and to ensure x is owned by Obj directly, use if (obj.hasOwnProperty(x))....
Otherwise, when using a simple object and not being worried about the object's prototype chain, using if (typeof(obj[x]) !== 'undefined')... is the safest and fastest way.
If you use a simple object as a hash table and never do anything kinky, I would use if (obj[x])... as I find it much more readable.
Yes it is :) I think you can also do Object.prototype.hasOwnProperty.call(x, 'key') which should also work if x has a property called hasOwnProperty :)
But that tests for own properties. If you want to check if it has an property that may also be inhered you can use typeof x.foo != 'undefined'.
if(x.hasOwnProperty("key")){
// …
}
because
if(x.key){
// …
}
fails if x.key is falsy (for example, x.key === "").
You can also use the ES6 Reflect object:
x = {'key': 1};
Reflect.has( x, 'key'); // returns true
Documentation on MDN for Reflect.has can be found here.
The static Reflect.has() method works like the in operator as a function.
Do not do this object.hasOwnProperty(key)). It's really bad because these methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false } - or, the object may be a null object (Object.create(null)).
The best way is to do Object.prototype.hasOwnProperty.call(object, key) or:
const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(object, key));
/* Or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));
OK, it looks like I had the right answer unless if you don't want inherited properties:
if (x.hasOwnProperty('key'))
Here are some other options to include inherited properties:
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)
Another relatively simple way is using Object.keys. This returns an array which means you get all of the features of an array.
var noInfo = {};
var info = {something: 'data'};
Object.keys(noInfo).length //returns 0 or false
Object.keys(info).length //returns 1 or true
Although we are in a world with great browser support. Because this question is so old I thought I'd add this:
This is safe to use as of JavaScript v1.8.5.
JavaScript is now evolving and growing as it now has good and even efficient ways to check it.
Here are some easy ways to check if object has a particular property:
Using hasOwnProperty()
const hero = {
name: 'Batman'
};
hero.hasOwnProperty('name'); // => true
hero.hasOwnProperty('realName'); // => false
Using keyword/operator in
const hero = {
name: 'Batman'
};
'name' in hero; // => true
'realName' in hero; // => false
Comparing with undefined keyword
const hero = {
name: 'Batman'
};
hero.name; // => 'Batman'
hero.realName; // => undefined
// So consider this
hero.realName == undefined // => true (which means property does not exists in object)
hero.name == undefined // => false (which means that property exists in object)
For more information, check here.
hasOwnProperty "can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain."
So most probably, for what seems by your question, you don't want to use hasOwnProperty, which determines if the property exists as attached directly to the object itself,.
If you want to determine if the property exists in the prototype chain, you may want to use it like:
if (prop in object) { // Do something }
You can use the following approaches-
var obj = {a:1}
console.log('a' in obj) // 1
console.log(obj.hasOwnProperty('a')) // 2
console.log(Boolean(obj.a)) // 3
The difference between the following approaches are as follows-
In the first and third approach we are not just searching in object but its prototypal chain too. If the object does not have the property, but the property is present in its prototype chain it is going to give true.
var obj = {
a: 2,
__proto__ : {b: 2}
}
console.log('b' in obj)
console.log(Boolean(obj.b))
The second approach will check only for its own properties. Example -
var obj = {
a: 2,
__proto__ : {b: 2}
}
console.log(obj.hasOwnProperty('b'))
The difference between the first and the third is if there is a property which has value undefined the third approach is going to give false while first will give true.
var obj = {
b : undefined
}
console.log(Boolean(obj.b))
console.log('b' in obj);
Given myObject object and “myKey” as key name:
Object.keys(myObject).includes('myKey')
or
myObject.hasOwnProperty('myKey')
or
typeof myObject.myKey !== 'undefined'
The last was widely used, but (as pointed out in other answers and comments) it could also match on keys deriving from Object prototype.
Performance
Today 2020.12.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.
Results
I compare only solutions A-F because they give valid result for all cased used in snippet in details section. For all browsers
solution based on in (A) is fast or fastest
solution (E) is fastest for chrome for big objects and fastest for firefox for small arrays if key not exists
solution (F) is fastest (~ >10x than other solutions) for small arrays
solutions (D,E) are quite fast
solution based on losash has (B) is slowest
Details
I perform 4 tests cases:
when object has 10 fields and searched key exists - you can run it HERE
when object has 10 fields and searched key not exists - you can run it HERE
when object has 10000 fields and searched key exists - you can run it HERE
when object has 10000 fields and searched key exists - you can run it HERE
Below snippet presents differences between solutions
A
B
C
D
E
F
G
H
I
J
K
// SO https://stackoverflow.com/q/135448/860099
// src: https://stackoverflow.com/a/14664748/860099
function A(x) {
return 'key' in x
}
// src: https://stackoverflow.com/a/11315692/860099
function B(x) {
return _.has(x, 'key')
}
// src: https://stackoverflow.com/a/40266120/860099
function C(x) {
return Reflect.has( x, 'key')
}
// src: https://stackoverflow.com/q/135448/860099
function D(x) {
return x.hasOwnProperty('key')
}
// src: https://stackoverflow.com/a/11315692/860099
function E(x) {
return Object.prototype.hasOwnProperty.call(x, 'key')
}
// src: https://stackoverflow.com/a/136411/860099
function F(x) {
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
return hasOwnProperty(x,'key')
}
// src: https://stackoverflow.com/a/135568/860099
function G(x) {
return typeof(x.key) !== 'undefined'
}
// src: https://stackoverflow.com/a/22740939/860099
function H(x) {
return x.key !== undefined
}
// src: https://stackoverflow.com/a/38332171/860099
function I(x) {
return !!x.key
}
// src: https://stackoverflow.com/a/41184688/860099
function J(x) {
return !!x['key']
}
// src: https://stackoverflow.com/a/54196605/860099
function K(x) {
return Boolean(x.key)
}
// --------------------
// TEST
// --------------------
let x1 = {'key': 1};
let x2 = {'key': "1"};
let x3 = {'key': true};
let x4 = {'key': []};
let x5 = {'key': {}};
let x6 = {'key': ()=>{}};
let x7 = {'key': ''};
let x8 = {'key': 0};
let x9 = {'key': false};
let x10= {'key': undefined};
let x11= {'nokey': 1};
let b= x=> x ? 1:0;
console.log(' 1 2 3 4 5 6 7 8 9 10 11');
[A,B,C,D,E,F,G,H,I,J,K ].map(f=> {
console.log(
`${f.name} ${b(f(x1))} ${b(f(x2))} ${b(f(x3))} ${b(f(x4))} ${b(f(x5))} ${b(f(x6))} ${b(f(x7))} ${b(f(x8))} ${b(f(x9))} ${b(f(x10))} ${b(f(x11))} `
)})
console.log('\nLegend: Columns (cases)');
console.log('1. key = 1 ');
console.log('2. key = "1" ');
console.log('3. key = true ');
console.log('4. key = [] ');
console.log('5. key = {} ');
console.log('6. key = ()=>{} ');
console.log('7. key = "" ');
console.log('8. key = 0 ');
console.log('9. key = false ');
console.log('10. key = undefined ');
console.log('11. no-key ');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome
Now with ECMAScript22 we can use hasOwn instead of hasOwnProperty (Because this feature has pitfalls )
Object.hasOwn(obj, propKey)
Here is another option for a specific case. :)
If you want to test for a member on an object and want to know if it has been set to something other than:
''
false
null
undefined
0
...
then you can use:
var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
// member is set, do something
}
some easier and short options depending on the specific use case:
to check if the property exists, regardless of value, use the in operator ("a" in b)
to check a property value from a variable, use bracket notation (obj[v])
to check a property value as truthy, use optional
chaining (?.)
to check a property value boolean, use double-not / bang-bang / (!!)
to set a default value for null / undefined check, use nullish coalescing operator (??)
to set a default value for falsey value check, use short-circuit logical OR operator (||)
run the code snippet to see results:
let obj1 = {prop:undefined};
console.log(1,"prop" in obj1);
console.log(1,obj1?.prop);
let obj2 = undefined;
//console.log(2,"prop" in obj2); would throw because obj2 undefined
console.log(2,"prop" in (obj2 ?? {}))
console.log(2,obj2?.prop);
let obj3 = {prop:false};
console.log(3,"prop" in obj3);
console.log(3,!!obj3?.prop);
let obj4 = {prop:null};
let look = "prop"
console.log(4,"prop" in obj4);
console.log(4,obj4?.[look]);
let obj5 = {prop:true};
console.log(5,"prop" in obj5);
console.log(5,obj5?.prop === true);
let obj6 = {otherProp:true};
look = "otherProp"
console.log(6,"prop" in obj6);
console.log(6,obj6.look); //should have used bracket notation
let obj7 = {prop:""};
console.log(7,"prop" in obj7);
console.log(7,obj7?.prop || "empty");
I see very few instances where hasOwn is used properly, especially given its inheritance issues
There is a method, "hasOwnProperty", that exists on an object, but it's not recommended to call this method directly, because it might be sometimes that the object is null or some property exist on the object like: { hasOwnProperty: false }
So a better way would be:
// Good
var obj = {"bar": "here bar desc"}
console.log(Object.prototype.hasOwnProperty.call(obj, "bar"));
// Best
const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(obj, "bar"));
An ECMAScript 6 solution with reflection. Create a wrapper like:
/**
Gets an argument from array or object.
The possible outcome:
- If the key exists the value is returned.
- If no key exists the default value is returned.
- If no default value is specified an empty string is returned.
#param obj The object or array to be searched.
#param key The name of the property or key.
#param defVal Optional default version of the command-line parameter [default ""]
#return The default value in case of an error else the found parameter.
*/
function getSafeReflectArg( obj, key, defVal) {
"use strict";
var retVal = (typeof defVal === 'undefined' ? "" : defVal);
if ( Reflect.has( obj, key) ) {
return Reflect.get( obj, key);
}
return retVal;
} // getSafeReflectArg
Showing how to use this answer
const object= {key1: 'data', key2: 'data2'};
Object.keys(object).includes('key1') //returns true
We can use indexOf as well, I prefer includes
You need to use the method object.hasOwnProperty(property). It returns true if the object has the property and false if the object doesn't.
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true
console.log(object1.hasOwnProperty('toString'));
// expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false
Know more
Don't over-complicate things when you can do:
var isProperty = (objectname.keyname || "") ? true : false;
It Is simple and clear for most cases...
A Better approach for iterating on object's own properties:
If you want to iterate on object's properties without using hasOwnProperty() check,
use for(let key of Object.keys(stud)){} method:
for(let key of Object.keys(stud)){
console.log(key); // will only log object's Own properties
}
full Example and comparison with for-in with hasOwnProperty()
function Student() {
this.name = "nitin";
}
Student.prototype = {
grade: 'A'
}
let stud = new Student();
// for-in approach
for(let key in stud){
if(stud.hasOwnProperty(key)){
console.log(key); // only outputs "name"
}
}
//Object.keys() approach
for(let key of Object.keys(stud)){
console.log(key);
}

Difference between checking the value of an object's property and checking if a property is in an object [duplicate]

How do I check if an object has a specific property in JavaScript?
Consider:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
Is that the best way to do it?
2022 UPDATE
Object.hasOwn()
Object.hasOwn() is recommended over Object.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive.
Example
const object1 = {
prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));
// expected output: true
Original answer
I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results.
It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)
If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object will give you your desired effect.
Since using hasOwnProperty is probably what you want, and considering that you may want a fallback method, I present to you the following solution:
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
The above is a working, cross-browser, solution to hasOwnProperty(), with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.
With Underscore.js or (even better) Lodash:
_.has(x, 'key');
Which calls Object.prototype.hasOwnProperty, but (a) is shorter to type, and (b) uses "a safe reference to hasOwnProperty" (i.e. it works even if hasOwnProperty is overwritten).
In particular, Lodash defines _.has as:
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
// hasOwnProperty = Object.prototype.hasOwnProperty
You can use this (but read the warning below):
var x = {
'key': 1
};
if ('key' in x) {
console.log('has');
}
But be warned: 'constructor' in x will return true even if x is an empty object - same for 'toString' in x, and many others. It's better to use Object.hasOwn(x, 'key').
Note: the following is nowadays largely obsolete thanks to strict mode, and hasOwnProperty. The correct solution is to use strict mode and to check for the presence of a property using obj.hasOwnProperty. This answer predates both these things, at least as widely implemented (yes, it is that old). Take the following as a historical note.
Bear in mind that undefined is (unfortunately) not a reserved word in JavaScript if you’re not using strict mode. Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.
A more robust method is therefore the following:
if (typeof(x.attribute) !== 'undefined')
On the flip side, this method is much more verbose and also slower. :-/
A common alternative is to ensure that undefined is actually undefined, e.g. by putting the code into a function which accepts an additional parameter, called undefined, that isn’t passed a value. To ensure that it’s not passed a value, you could just call it yourself immediately, e.g.:
(function (undefined) {
… your code …
if (x.attribute !== undefined)
… mode code …
})();
if (x.key !== undefined)
Armin Ronacher seems to have already beat me to it, but:
Object.prototype.hasOwnProperty = function(property) {
return this[property] !== undefined;
};
x = {'key': 1};
if (x.hasOwnProperty('key')) {
alert('have key!');
}
if (!x.hasOwnProperty('bar')) {
alert('no bar!');
}
A safer, but slower solution, as pointed out by Konrad Rudolph and Armin Ronacher would be:
Object.prototype.hasOwnProperty = function(property) {
return typeof this[property] !== 'undefined';
};
Considering the following object in Javascript
const x = {key: 1};
You can use the in operator to check if the property exists on an object:
console.log("key" in x);
You can also loop through all the properties of the object using a for - in loop, and then check for the specific property:
for (const prop in x) {
if (prop === "key") {
//Do something
}
}
You must consider if this object property is enumerable or not, because non-enumerable properties will not show up in a for-in loop. Also, if the enumerable property is shadowing a non-enumerable property of the prototype, it will not show up in Internet Explorer 8 and earlier.
If you’d like a list of all instance properties, whether enumerable or not, you can use
Object.getOwnPropertyNames(x);
This will return an array of names of all properties that exist on an object.
Reflections provide methods that can be used to interact with Javascript objects. The static Reflect.has() method works like the in operator as a function.
console.log(Reflect.has(x, 'key'));
// expected output: true
console.log(Reflect.has(x, 'key2'));
// expected output: false
console.log(Reflect.has(object1, 'toString'));
// expected output: true
Finally, you can use the typeof operator to directly check the data type of the object property:
if (typeof x.key === "undefined") {
console.log("undefined");
}
If the property does not exist on the object, it will return the string undefined. Else it will return the appropriate property type. However, note that this is not always a valid way of checking if an object has a property or not, because you could have a property that is set to undefined, in which case, using typeof x.key would still return true (even though the key is still in the object).
Similarly, you can check if a property exists by comparing directly to the undefined Javascript property
if (x.key === undefined) {
console.log("undefined");
}
This should work unless key was specifically set to undefined on the x object
Let's cut through some confusion here. First, let's simplify by assuming hasOwnProperty already exists; this is true of the vast majority of current browsers in use.
hasOwnProperty returns true if the attribute name that is passed to it has been added to the object. It is entirely independent of the actual value assigned to it which may be exactly undefined.
Hence:
var o = {}
o.x = undefined
var a = o.hasOwnProperty('x') // a is true
var b = o.x === undefined // b is also true
However:
var o = {}
var a = o.hasOwnProperty('x') // a is now false
var b = o.x === undefined // b is still true
The problem is what happens when an object in the prototype chain has an attribute with the value of undefined? hasOwnProperty will be false for it, and so will !== undefined. Yet, for..in will still list it in the enumeration.
The bottom line is there is no cross-browser way (since Internet Explorer doesn't expose __prototype__) to determine that a specific identifier has not been attached to an object or anything in its prototype chain.
If you are searching for a property, then "no". You want:
if ('prop' in obj) { }
In general, you should not care whether or not the property comes from the prototype or the object.
However, because you used 'key' in your sample code, it looks like you are treating the object as a hash, in which case your answer would make sense. All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.
John Resig's answer was very comprehensive, but I thought it wasn't clear. Especially with when to use "'prop' in obj".
For testing simple objects, use:
if (obj[x] !== undefined)
If you don't know what object type it is, use:
if (obj.hasOwnProperty(x))
All other options are slower...
Details
A performance evaluation of 100,000,000 cycles under Node.js to the five options suggested by others here:
function hasKey1(k,o) { return (x in obj); }
function hasKey2(k,o) { return (obj[x]); }
function hasKey3(k,o) { return (obj[x] !== undefined); }
function hasKey4(k,o) { return (typeof(obj[x]) !== 'undefined'); }
function hasKey5(k,o) { return (obj.hasOwnProperty(x)); }
The evaluation tells us that unless we specifically want to check the object's prototype chain as well as the object itself, we should not use the common form:
if (X in Obj)...
It is between 2 to 6 times slower depending on the use case
hasKey1 execution time: 4.51 s
hasKey2 execution time: 0.90 s
hasKey3 execution time: 0.76 s
hasKey4 execution time: 0.93 s
hasKey5 execution time: 2.15 s
Bottom line, if your Obj is not necessarily a simple object and you wish to avoid checking the object's prototype chain and to ensure x is owned by Obj directly, use if (obj.hasOwnProperty(x))....
Otherwise, when using a simple object and not being worried about the object's prototype chain, using if (typeof(obj[x]) !== 'undefined')... is the safest and fastest way.
If you use a simple object as a hash table and never do anything kinky, I would use if (obj[x])... as I find it much more readable.
Yes it is :) I think you can also do Object.prototype.hasOwnProperty.call(x, 'key') which should also work if x has a property called hasOwnProperty :)
But that tests for own properties. If you want to check if it has an property that may also be inhered you can use typeof x.foo != 'undefined'.
if(x.hasOwnProperty("key")){
// …
}
because
if(x.key){
// …
}
fails if x.key is falsy (for example, x.key === "").
You can also use the ES6 Reflect object:
x = {'key': 1};
Reflect.has( x, 'key'); // returns true
Documentation on MDN for Reflect.has can be found here.
The static Reflect.has() method works like the in operator as a function.
Do not do this object.hasOwnProperty(key)). It's really bad because these methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false } - or, the object may be a null object (Object.create(null)).
The best way is to do Object.prototype.hasOwnProperty.call(object, key) or:
const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(object, key));
/* Or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));
OK, it looks like I had the right answer unless if you don't want inherited properties:
if (x.hasOwnProperty('key'))
Here are some other options to include inherited properties:
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)
Another relatively simple way is using Object.keys. This returns an array which means you get all of the features of an array.
var noInfo = {};
var info = {something: 'data'};
Object.keys(noInfo).length //returns 0 or false
Object.keys(info).length //returns 1 or true
Although we are in a world with great browser support. Because this question is so old I thought I'd add this:
This is safe to use as of JavaScript v1.8.5.
JavaScript is now evolving and growing as it now has good and even efficient ways to check it.
Here are some easy ways to check if object has a particular property:
Using hasOwnProperty()
const hero = {
name: 'Batman'
};
hero.hasOwnProperty('name'); // => true
hero.hasOwnProperty('realName'); // => false
Using keyword/operator in
const hero = {
name: 'Batman'
};
'name' in hero; // => true
'realName' in hero; // => false
Comparing with undefined keyword
const hero = {
name: 'Batman'
};
hero.name; // => 'Batman'
hero.realName; // => undefined
// So consider this
hero.realName == undefined // => true (which means property does not exists in object)
hero.name == undefined // => false (which means that property exists in object)
For more information, check here.
hasOwnProperty "can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain."
So most probably, for what seems by your question, you don't want to use hasOwnProperty, which determines if the property exists as attached directly to the object itself,.
If you want to determine if the property exists in the prototype chain, you may want to use it like:
if (prop in object) { // Do something }
You can use the following approaches-
var obj = {a:1}
console.log('a' in obj) // 1
console.log(obj.hasOwnProperty('a')) // 2
console.log(Boolean(obj.a)) // 3
The difference between the following approaches are as follows-
In the first and third approach we are not just searching in object but its prototypal chain too. If the object does not have the property, but the property is present in its prototype chain it is going to give true.
var obj = {
a: 2,
__proto__ : {b: 2}
}
console.log('b' in obj)
console.log(Boolean(obj.b))
The second approach will check only for its own properties. Example -
var obj = {
a: 2,
__proto__ : {b: 2}
}
console.log(obj.hasOwnProperty('b'))
The difference between the first and the third is if there is a property which has value undefined the third approach is going to give false while first will give true.
var obj = {
b : undefined
}
console.log(Boolean(obj.b))
console.log('b' in obj);
Given myObject object and “myKey” as key name:
Object.keys(myObject).includes('myKey')
or
myObject.hasOwnProperty('myKey')
or
typeof myObject.myKey !== 'undefined'
The last was widely used, but (as pointed out in other answers and comments) it could also match on keys deriving from Object prototype.
Performance
Today 2020.12.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.
Results
I compare only solutions A-F because they give valid result for all cased used in snippet in details section. For all browsers
solution based on in (A) is fast or fastest
solution (E) is fastest for chrome for big objects and fastest for firefox for small arrays if key not exists
solution (F) is fastest (~ >10x than other solutions) for small arrays
solutions (D,E) are quite fast
solution based on losash has (B) is slowest
Details
I perform 4 tests cases:
when object has 10 fields and searched key exists - you can run it HERE
when object has 10 fields and searched key not exists - you can run it HERE
when object has 10000 fields and searched key exists - you can run it HERE
when object has 10000 fields and searched key exists - you can run it HERE
Below snippet presents differences between solutions
A
B
C
D
E
F
G
H
I
J
K
// SO https://stackoverflow.com/q/135448/860099
// src: https://stackoverflow.com/a/14664748/860099
function A(x) {
return 'key' in x
}
// src: https://stackoverflow.com/a/11315692/860099
function B(x) {
return _.has(x, 'key')
}
// src: https://stackoverflow.com/a/40266120/860099
function C(x) {
return Reflect.has( x, 'key')
}
// src: https://stackoverflow.com/q/135448/860099
function D(x) {
return x.hasOwnProperty('key')
}
// src: https://stackoverflow.com/a/11315692/860099
function E(x) {
return Object.prototype.hasOwnProperty.call(x, 'key')
}
// src: https://stackoverflow.com/a/136411/860099
function F(x) {
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
return hasOwnProperty(x,'key')
}
// src: https://stackoverflow.com/a/135568/860099
function G(x) {
return typeof(x.key) !== 'undefined'
}
// src: https://stackoverflow.com/a/22740939/860099
function H(x) {
return x.key !== undefined
}
// src: https://stackoverflow.com/a/38332171/860099
function I(x) {
return !!x.key
}
// src: https://stackoverflow.com/a/41184688/860099
function J(x) {
return !!x['key']
}
// src: https://stackoverflow.com/a/54196605/860099
function K(x) {
return Boolean(x.key)
}
// --------------------
// TEST
// --------------------
let x1 = {'key': 1};
let x2 = {'key': "1"};
let x3 = {'key': true};
let x4 = {'key': []};
let x5 = {'key': {}};
let x6 = {'key': ()=>{}};
let x7 = {'key': ''};
let x8 = {'key': 0};
let x9 = {'key': false};
let x10= {'key': undefined};
let x11= {'nokey': 1};
let b= x=> x ? 1:0;
console.log(' 1 2 3 4 5 6 7 8 9 10 11');
[A,B,C,D,E,F,G,H,I,J,K ].map(f=> {
console.log(
`${f.name} ${b(f(x1))} ${b(f(x2))} ${b(f(x3))} ${b(f(x4))} ${b(f(x5))} ${b(f(x6))} ${b(f(x7))} ${b(f(x8))} ${b(f(x9))} ${b(f(x10))} ${b(f(x11))} `
)})
console.log('\nLegend: Columns (cases)');
console.log('1. key = 1 ');
console.log('2. key = "1" ');
console.log('3. key = true ');
console.log('4. key = [] ');
console.log('5. key = {} ');
console.log('6. key = ()=>{} ');
console.log('7. key = "" ');
console.log('8. key = 0 ');
console.log('9. key = false ');
console.log('10. key = undefined ');
console.log('11. no-key ');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome
Now with ECMAScript22 we can use hasOwn instead of hasOwnProperty (Because this feature has pitfalls )
Object.hasOwn(obj, propKey)
Here is another option for a specific case. :)
If you want to test for a member on an object and want to know if it has been set to something other than:
''
false
null
undefined
0
...
then you can use:
var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
// member is set, do something
}
some easier and short options depending on the specific use case:
to check if the property exists, regardless of value, use the in operator ("a" in b)
to check a property value from a variable, use bracket notation (obj[v])
to check a property value as truthy, use optional
chaining (?.)
to check a property value boolean, use double-not / bang-bang / (!!)
to set a default value for null / undefined check, use nullish coalescing operator (??)
to set a default value for falsey value check, use short-circuit logical OR operator (||)
run the code snippet to see results:
let obj1 = {prop:undefined};
console.log(1,"prop" in obj1);
console.log(1,obj1?.prop);
let obj2 = undefined;
//console.log(2,"prop" in obj2); would throw because obj2 undefined
console.log(2,"prop" in (obj2 ?? {}))
console.log(2,obj2?.prop);
let obj3 = {prop:false};
console.log(3,"prop" in obj3);
console.log(3,!!obj3?.prop);
let obj4 = {prop:null};
let look = "prop"
console.log(4,"prop" in obj4);
console.log(4,obj4?.[look]);
let obj5 = {prop:true};
console.log(5,"prop" in obj5);
console.log(5,obj5?.prop === true);
let obj6 = {otherProp:true};
look = "otherProp"
console.log(6,"prop" in obj6);
console.log(6,obj6.look); //should have used bracket notation
let obj7 = {prop:""};
console.log(7,"prop" in obj7);
console.log(7,obj7?.prop || "empty");
I see very few instances where hasOwn is used properly, especially given its inheritance issues
There is a method, "hasOwnProperty", that exists on an object, but it's not recommended to call this method directly, because it might be sometimes that the object is null or some property exist on the object like: { hasOwnProperty: false }
So a better way would be:
// Good
var obj = {"bar": "here bar desc"}
console.log(Object.prototype.hasOwnProperty.call(obj, "bar"));
// Best
const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(obj, "bar"));
An ECMAScript 6 solution with reflection. Create a wrapper like:
/**
Gets an argument from array or object.
The possible outcome:
- If the key exists the value is returned.
- If no key exists the default value is returned.
- If no default value is specified an empty string is returned.
#param obj The object or array to be searched.
#param key The name of the property or key.
#param defVal Optional default version of the command-line parameter [default ""]
#return The default value in case of an error else the found parameter.
*/
function getSafeReflectArg( obj, key, defVal) {
"use strict";
var retVal = (typeof defVal === 'undefined' ? "" : defVal);
if ( Reflect.has( obj, key) ) {
return Reflect.get( obj, key);
}
return retVal;
} // getSafeReflectArg
Showing how to use this answer
const object= {key1: 'data', key2: 'data2'};
Object.keys(object).includes('key1') //returns true
We can use indexOf as well, I prefer includes
You need to use the method object.hasOwnProperty(property). It returns true if the object has the property and false if the object doesn't.
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true
console.log(object1.hasOwnProperty('toString'));
// expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false
Know more
Don't over-complicate things when you can do:
var isProperty = (objectname.keyname || "") ? true : false;
It Is simple and clear for most cases...
A Better approach for iterating on object's own properties:
If you want to iterate on object's properties without using hasOwnProperty() check,
use for(let key of Object.keys(stud)){} method:
for(let key of Object.keys(stud)){
console.log(key); // will only log object's Own properties
}
full Example and comparison with for-in with hasOwnProperty()
function Student() {
this.name = "nitin";
}
Student.prototype = {
grade: 'A'
}
let stud = new Student();
// for-in approach
for(let key in stud){
if(stud.hasOwnProperty(key)){
console.log(key); // only outputs "name"
}
}
//Object.keys() approach
for(let key of Object.keys(stud)){
console.log(key);
}

Access sub-property with generic/dynamic property list [duplicate]

I have a bunch of object attributes coming in as dot-delimited strings like "availability_meta.supplier.price", and I need to assign a corresponding value to record['availability_meta']['supplier']['price'] and so on.
Not everything is 3 levels deep: many are only 1 level deep and many are deeper than 3 levels.
Is there a good way to assign this programmatically in Javascript? For example, I need:
["foo.bar.baz", 1] // --> record.foo.bar.baz = 1
["qux.qaz", "abc"] // --> record.qux.qaz = "abc"
["foshizzle", 200] // --> record.foshizzle = 200
I imagine I could hack something together, but I don't have any good algorithm in mind so would appreciate suggestions. I'm using lodash if that's helpful, and open to other libraries that may make quick work of this.
EDIT this is on the backend and run infrequently, so not necessary to optimize for size, speed, etc. In fact code readability would be a plus here for future devs.
EDIT 2 This is NOT the same as the referenced duplicate. Namely, I need to be able to do this assignment multiple times for the same object, and the "duplicate" answer will simply overwrite sub-keys each time. Please reopen!
You mentioned lodash in your question, so I thought I should add their easy object set() and get() functions. Just do something like:
_.set(record, 'availability_meta.supplier.price', 99);
You can read more about it here: https://lodash.com/docs#set
These functions let you do more complex things too, like specify array indexes, etc :)
Something to get you started:
function assignProperty(obj, path, value) {
var props = path.split(".")
, i = 0
, prop;
for(; i < props.length - 1; i++) {
prop = props[i];
obj = obj[prop];
}
obj[props[i]] = value;
}
Assuming:
var arr = ["foo.bar.baz", 1];
You'd call it using:
assignProperty(record, arr[0], arr[1]);
Example: http://jsfiddle.net/x49g5w8L/
What about this?
function convertDotPathToNestedObject(path, value) {
const [last, ...paths] = path.split('.').reverse();
return paths.reduce((acc, el) => ({ [el]: acc }), { [last]: value });
}
convertDotPathToNestedObject('foo.bar.x', 'FooBar')
// { foo: { bar: { x: 'FooBar' } } }
Just do
record['foo.bar.baz'] = 99;
But how would this work? It's strictly for the adventurous with a V8 environment (Chrome or Node harmony), using Object.observe. We observe the the object and capture the addition of new properties. When the "property" foo.bar.baz is added (via an assignment), we detect that this is a dotted property, and transform it into an assignment to record['foo']['bar.baz'] (creating record['foo'] if it does not exist), which in turn is transformed into an assignment to record['foo']['bar']['baz']. It goes like this:
function enable_dot_assignments(changes) {
// Iterate over changes
changes.forEach(function(change) {
// Deconstruct change record.
var object = change.object;
var type = change.type;
var name = change.name;
// Handle only 'add' type changes
if (type !== 'add') return;
// Break the property into segments, and get first one.
var segments = name.split('.');
var first_segment = segments.shift();
// Skip non-dotted property.
if (!segments.length) return;
// If the property doesn't exist, create it as object.
if (!(first_segment in object)) object[first_segment] = {};
var subobject = object[first_segment];
// Ensure subobject also enables dot assignments.
Object.observe(subobject, enable_dot_assignments);
// Set value on subobject using remainder of dot path.
subobject[segments.join('.')] = object[name];
// Make subobject assignments synchronous.
Object.deliverChangeRecords(enable_dot_assignments);
// We don't need the 'a.b' property on the object.
delete object[name];
});
}
Now you can just do
Object.observe(record, enable_dot_assignments);
record['foo.bar.baz'] = 99;
Beware, however, that such assignments will be asynchronous, which may or may not work for you. To solve this, call Object.deliverChangeRecords immediately after the assignment. Or, although not as syntactically pleasing, you could write a helper function, also setting up the observer:
function dot_assignment(object, path, value) {
Object.observe(object, enable_dot_assignments);
object[path] = value;
Object.deliverChangeRecords(enable_dot_assignments);
}
dot_assignment(record, 'foo.bar.baz', 99);
Something like this example perhaps. It will extend a supplied object or create one if it no object is supplied. It is destructive in nature, if you supply keys that already exist in the object, but you can change that if that is not what you want. Uses ECMA5.
/*global console */
/*members split, pop, reduce, trim, forEach, log, stringify */
(function () {
'use strict';
function isObject(arg) {
return arg && typeof arg === 'object';
}
function convertExtend(arr, obj) {
if (!isObject(obj)) {
obj = {};
}
var str = arr[0],
last = obj,
props,
valProp;
if (typeof str === 'string') {
props = str.split('.');
valProp = props.pop();
props.reduce(function (nest, prop) {
prop = prop.trim();
last = nest[prop];
if (!isObject(last)) {
nest[prop] = last = {};
}
return last;
}, obj);
last[valProp] = arr[1];
}
return obj;
}
var x = ['fum'],
y = [
['foo.bar.baz', 1],
['foo.bar.fum', new Date()],
['qux.qaz', 'abc'],
['foshizzle', 200]
],
z = ['qux.qux', null],
record = convertExtend(x);
y.forEach(function (yi) {
convertExtend(yi, record);
});
convertExtend(z, record);
document.body.textContent = JSON.stringify(record, function (key, value, Undefined) {
/*jslint unparam:true */
/*jshint unused:false */
if (value === Undefined) {
value = String(value);
}
return value;
});
}());
it's an old question, but if anyone still looking for a solution can try this
function restructureObject(object){
let result = {};
for(let key in object){
const splittedKeys = key.split('.');
if(splittedKeys.length === 1){
result[key] = object[key];
}
else if(splittedKeys.length > 2){
result = {...result, ...{[splittedKeys.splice(0,1)]: {}} ,...restructureObject({[splittedKeys.join('.')]: object[key]})}
}else{
result[splittedKeys[0]] = {[splittedKeys[1]]: object[key]}
}
}
return result
}

underscore.js every() with undefined

I wrote some code like this:
var a = new Array(10); // should be [undefined * 10]
var b = _.every(a, function(m){
if(_.isUndefined(m)){
return false;
}
return true;
});
I expect b is 'false', but it return 'true'.
Why it return 'true'?
Then, I change to this:
var c = [undefined, undefined];
var d = _.every(c, function(m){
if(_.isUndefined(m)){
return false;
}
return true;
});
it return 'false' in d.
Why they are different?
You can test this in http://jsfiddle.net/3qj4B/3/
When you create an array using the class initializer you are creating an array with 10 space of memory available to be used, but none of them is yet initialized. So you're not looping over anything.
Now look at the source of every:
_.every = _.all = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
result is set to be true and it is returned since each does no iterations. That's why you're returning true.
If, in your fiddle, you try to add a console.log(m) inside the handler you'll see no logs in the console since each iterates 0 times.
There's a subtle difference between initializing an array with the Array constructor and an initial size, and initializing with an explicit list of undefined entries. The former (the Array constructor) doesn't create properties corresponding to the indexes, while the explicit initialization does.
I suspect that Underscore is using the native .forEach() when it can, and that won't call its callback for uninitialized indexes. Thus, in the first test, the callback to _.every() is never being called at all.
edit — the Array constructor does something more-or-less the same as:
var a = []; a.length = 10;
When you extend an array by increasing its length like that, the new implicit index positions aren't initialized. It's the basic difference between the non-existence of a property, and the presence of a property with no value. In both cases, a dereference of the property results in undefined. Thus:
var o = {};
if (o.something == undefined) // this will be true
and then:
var o = { something: undefined };
if (o.something == undefined) // also true
One way to tell the difference between the two situations is the in operator:
if ('something' in o) // only true in the second case

How do I check if an object has a specific property in JavaScript?

How do I check if an object has a specific property in JavaScript?
Consider:
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
Is that the best way to do it?
2022 UPDATE
Object.hasOwn()
Object.hasOwn() is recommended over Object.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive.
Example
const object1 = {
prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));
// expected output: true
Original answer
I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results.
It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)
If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object will give you your desired effect.
Since using hasOwnProperty is probably what you want, and considering that you may want a fallback method, I present to you the following solution:
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
The above is a working, cross-browser, solution to hasOwnProperty(), with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.
With Underscore.js or (even better) Lodash:
_.has(x, 'key');
Which calls Object.prototype.hasOwnProperty, but (a) is shorter to type, and (b) uses "a safe reference to hasOwnProperty" (i.e. it works even if hasOwnProperty is overwritten).
In particular, Lodash defines _.has as:
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
// hasOwnProperty = Object.prototype.hasOwnProperty
You can use this (but read the warning below):
var x = {
'key': 1
};
if ('key' in x) {
console.log('has');
}
But be warned: 'constructor' in x will return true even if x is an empty object - same for 'toString' in x, and many others. It's better to use Object.hasOwn(x, 'key').
Note: the following is nowadays largely obsolete thanks to strict mode, and hasOwnProperty. The correct solution is to use strict mode and to check for the presence of a property using obj.hasOwnProperty. This answer predates both these things, at least as widely implemented (yes, it is that old). Take the following as a historical note.
Bear in mind that undefined is (unfortunately) not a reserved word in JavaScript if you’re not using strict mode. Therefore, someone (someone else, obviously) could have the grand idea of redefining it, breaking your code.
A more robust method is therefore the following:
if (typeof(x.attribute) !== 'undefined')
On the flip side, this method is much more verbose and also slower. :-/
A common alternative is to ensure that undefined is actually undefined, e.g. by putting the code into a function which accepts an additional parameter, called undefined, that isn’t passed a value. To ensure that it’s not passed a value, you could just call it yourself immediately, e.g.:
(function (undefined) {
… your code …
if (x.attribute !== undefined)
… mode code …
})();
if (x.key !== undefined)
Armin Ronacher seems to have already beat me to it, but:
Object.prototype.hasOwnProperty = function(property) {
return this[property] !== undefined;
};
x = {'key': 1};
if (x.hasOwnProperty('key')) {
alert('have key!');
}
if (!x.hasOwnProperty('bar')) {
alert('no bar!');
}
A safer, but slower solution, as pointed out by Konrad Rudolph and Armin Ronacher would be:
Object.prototype.hasOwnProperty = function(property) {
return typeof this[property] !== 'undefined';
};
Considering the following object in Javascript
const x = {key: 1};
You can use the in operator to check if the property exists on an object:
console.log("key" in x);
You can also loop through all the properties of the object using a for - in loop, and then check for the specific property:
for (const prop in x) {
if (prop === "key") {
//Do something
}
}
You must consider if this object property is enumerable or not, because non-enumerable properties will not show up in a for-in loop. Also, if the enumerable property is shadowing a non-enumerable property of the prototype, it will not show up in Internet Explorer 8 and earlier.
If you’d like a list of all instance properties, whether enumerable or not, you can use
Object.getOwnPropertyNames(x);
This will return an array of names of all properties that exist on an object.
Reflections provide methods that can be used to interact with Javascript objects. The static Reflect.has() method works like the in operator as a function.
console.log(Reflect.has(x, 'key'));
// expected output: true
console.log(Reflect.has(x, 'key2'));
// expected output: false
console.log(Reflect.has(object1, 'toString'));
// expected output: true
Finally, you can use the typeof operator to directly check the data type of the object property:
if (typeof x.key === "undefined") {
console.log("undefined");
}
If the property does not exist on the object, it will return the string undefined. Else it will return the appropriate property type. However, note that this is not always a valid way of checking if an object has a property or not, because you could have a property that is set to undefined, in which case, using typeof x.key would still return true (even though the key is still in the object).
Similarly, you can check if a property exists by comparing directly to the undefined Javascript property
if (x.key === undefined) {
console.log("undefined");
}
This should work unless key was specifically set to undefined on the x object
Let's cut through some confusion here. First, let's simplify by assuming hasOwnProperty already exists; this is true of the vast majority of current browsers in use.
hasOwnProperty returns true if the attribute name that is passed to it has been added to the object. It is entirely independent of the actual value assigned to it which may be exactly undefined.
Hence:
var o = {}
o.x = undefined
var a = o.hasOwnProperty('x') // a is true
var b = o.x === undefined // b is also true
However:
var o = {}
var a = o.hasOwnProperty('x') // a is now false
var b = o.x === undefined // b is still true
The problem is what happens when an object in the prototype chain has an attribute with the value of undefined? hasOwnProperty will be false for it, and so will !== undefined. Yet, for..in will still list it in the enumeration.
The bottom line is there is no cross-browser way (since Internet Explorer doesn't expose __prototype__) to determine that a specific identifier has not been attached to an object or anything in its prototype chain.
If you are searching for a property, then "no". You want:
if ('prop' in obj) { }
In general, you should not care whether or not the property comes from the prototype or the object.
However, because you used 'key' in your sample code, it looks like you are treating the object as a hash, in which case your answer would make sense. All of the hashes keys would be properties in the object, and you avoid the extra properties contributed by the prototype.
John Resig's answer was very comprehensive, but I thought it wasn't clear. Especially with when to use "'prop' in obj".
For testing simple objects, use:
if (obj[x] !== undefined)
If you don't know what object type it is, use:
if (obj.hasOwnProperty(x))
All other options are slower...
Details
A performance evaluation of 100,000,000 cycles under Node.js to the five options suggested by others here:
function hasKey1(k,o) { return (x in obj); }
function hasKey2(k,o) { return (obj[x]); }
function hasKey3(k,o) { return (obj[x] !== undefined); }
function hasKey4(k,o) { return (typeof(obj[x]) !== 'undefined'); }
function hasKey5(k,o) { return (obj.hasOwnProperty(x)); }
The evaluation tells us that unless we specifically want to check the object's prototype chain as well as the object itself, we should not use the common form:
if (X in Obj)...
It is between 2 to 6 times slower depending on the use case
hasKey1 execution time: 4.51 s
hasKey2 execution time: 0.90 s
hasKey3 execution time: 0.76 s
hasKey4 execution time: 0.93 s
hasKey5 execution time: 2.15 s
Bottom line, if your Obj is not necessarily a simple object and you wish to avoid checking the object's prototype chain and to ensure x is owned by Obj directly, use if (obj.hasOwnProperty(x))....
Otherwise, when using a simple object and not being worried about the object's prototype chain, using if (typeof(obj[x]) !== 'undefined')... is the safest and fastest way.
If you use a simple object as a hash table and never do anything kinky, I would use if (obj[x])... as I find it much more readable.
Yes it is :) I think you can also do Object.prototype.hasOwnProperty.call(x, 'key') which should also work if x has a property called hasOwnProperty :)
But that tests for own properties. If you want to check if it has an property that may also be inhered you can use typeof x.foo != 'undefined'.
if(x.hasOwnProperty("key")){
// …
}
because
if(x.key){
// …
}
fails if x.key is falsy (for example, x.key === "").
You can also use the ES6 Reflect object:
x = {'key': 1};
Reflect.has( x, 'key'); // returns true
Documentation on MDN for Reflect.has can be found here.
The static Reflect.has() method works like the in operator as a function.
Do not do this object.hasOwnProperty(key)). It's really bad because these methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false } - or, the object may be a null object (Object.create(null)).
The best way is to do Object.prototype.hasOwnProperty.call(object, key) or:
const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(object, key));
/* Or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));
OK, it looks like I had the right answer unless if you don't want inherited properties:
if (x.hasOwnProperty('key'))
Here are some other options to include inherited properties:
if (x.key) // Quick and dirty, but it does the same thing as below.
if (x.key !== undefined)
Another relatively simple way is using Object.keys. This returns an array which means you get all of the features of an array.
var noInfo = {};
var info = {something: 'data'};
Object.keys(noInfo).length //returns 0 or false
Object.keys(info).length //returns 1 or true
Although we are in a world with great browser support. Because this question is so old I thought I'd add this:
This is safe to use as of JavaScript v1.8.5.
JavaScript is now evolving and growing as it now has good and even efficient ways to check it.
Here are some easy ways to check if object has a particular property:
Using hasOwnProperty()
const hero = {
name: 'Batman'
};
hero.hasOwnProperty('name'); // => true
hero.hasOwnProperty('realName'); // => false
Using keyword/operator in
const hero = {
name: 'Batman'
};
'name' in hero; // => true
'realName' in hero; // => false
Comparing with undefined keyword
const hero = {
name: 'Batman'
};
hero.name; // => 'Batman'
hero.realName; // => undefined
// So consider this
hero.realName == undefined // => true (which means property does not exists in object)
hero.name == undefined // => false (which means that property exists in object)
For more information, check here.
hasOwnProperty "can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain."
So most probably, for what seems by your question, you don't want to use hasOwnProperty, which determines if the property exists as attached directly to the object itself,.
If you want to determine if the property exists in the prototype chain, you may want to use it like:
if (prop in object) { // Do something }
You can use the following approaches-
var obj = {a:1}
console.log('a' in obj) // 1
console.log(obj.hasOwnProperty('a')) // 2
console.log(Boolean(obj.a)) // 3
The difference between the following approaches are as follows-
In the first and third approach we are not just searching in object but its prototypal chain too. If the object does not have the property, but the property is present in its prototype chain it is going to give true.
var obj = {
a: 2,
__proto__ : {b: 2}
}
console.log('b' in obj)
console.log(Boolean(obj.b))
The second approach will check only for its own properties. Example -
var obj = {
a: 2,
__proto__ : {b: 2}
}
console.log(obj.hasOwnProperty('b'))
The difference between the first and the third is if there is a property which has value undefined the third approach is going to give false while first will give true.
var obj = {
b : undefined
}
console.log(Boolean(obj.b))
console.log('b' in obj);
Given myObject object and “myKey” as key name:
Object.keys(myObject).includes('myKey')
or
myObject.hasOwnProperty('myKey')
or
typeof myObject.myKey !== 'undefined'
The last was widely used, but (as pointed out in other answers and comments) it could also match on keys deriving from Object prototype.
Performance
Today 2020.12.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v83 for chosen solutions.
Results
I compare only solutions A-F because they give valid result for all cased used in snippet in details section. For all browsers
solution based on in (A) is fast or fastest
solution (E) is fastest for chrome for big objects and fastest for firefox for small arrays if key not exists
solution (F) is fastest (~ >10x than other solutions) for small arrays
solutions (D,E) are quite fast
solution based on losash has (B) is slowest
Details
I perform 4 tests cases:
when object has 10 fields and searched key exists - you can run it HERE
when object has 10 fields and searched key not exists - you can run it HERE
when object has 10000 fields and searched key exists - you can run it HERE
when object has 10000 fields and searched key exists - you can run it HERE
Below snippet presents differences between solutions
A
B
C
D
E
F
G
H
I
J
K
// SO https://stackoverflow.com/q/135448/860099
// src: https://stackoverflow.com/a/14664748/860099
function A(x) {
return 'key' in x
}
// src: https://stackoverflow.com/a/11315692/860099
function B(x) {
return _.has(x, 'key')
}
// src: https://stackoverflow.com/a/40266120/860099
function C(x) {
return Reflect.has( x, 'key')
}
// src: https://stackoverflow.com/q/135448/860099
function D(x) {
return x.hasOwnProperty('key')
}
// src: https://stackoverflow.com/a/11315692/860099
function E(x) {
return Object.prototype.hasOwnProperty.call(x, 'key')
}
// src: https://stackoverflow.com/a/136411/860099
function F(x) {
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
return hasOwnProperty(x,'key')
}
// src: https://stackoverflow.com/a/135568/860099
function G(x) {
return typeof(x.key) !== 'undefined'
}
// src: https://stackoverflow.com/a/22740939/860099
function H(x) {
return x.key !== undefined
}
// src: https://stackoverflow.com/a/38332171/860099
function I(x) {
return !!x.key
}
// src: https://stackoverflow.com/a/41184688/860099
function J(x) {
return !!x['key']
}
// src: https://stackoverflow.com/a/54196605/860099
function K(x) {
return Boolean(x.key)
}
// --------------------
// TEST
// --------------------
let x1 = {'key': 1};
let x2 = {'key': "1"};
let x3 = {'key': true};
let x4 = {'key': []};
let x5 = {'key': {}};
let x6 = {'key': ()=>{}};
let x7 = {'key': ''};
let x8 = {'key': 0};
let x9 = {'key': false};
let x10= {'key': undefined};
let x11= {'nokey': 1};
let b= x=> x ? 1:0;
console.log(' 1 2 3 4 5 6 7 8 9 10 11');
[A,B,C,D,E,F,G,H,I,J,K ].map(f=> {
console.log(
`${f.name} ${b(f(x1))} ${b(f(x2))} ${b(f(x3))} ${b(f(x4))} ${b(f(x5))} ${b(f(x6))} ${b(f(x7))} ${b(f(x8))} ${b(f(x9))} ${b(f(x10))} ${b(f(x11))} `
)})
console.log('\nLegend: Columns (cases)');
console.log('1. key = 1 ');
console.log('2. key = "1" ');
console.log('3. key = true ');
console.log('4. key = [] ');
console.log('5. key = {} ');
console.log('6. key = ()=>{} ');
console.log('7. key = "" ');
console.log('8. key = 0 ');
console.log('9. key = false ');
console.log('10. key = undefined ');
console.log('11. no-key ');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This shippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome
Now with ECMAScript22 we can use hasOwn instead of hasOwnProperty (Because this feature has pitfalls )
Object.hasOwn(obj, propKey)
Here is another option for a specific case. :)
If you want to test for a member on an object and want to know if it has been set to something other than:
''
false
null
undefined
0
...
then you can use:
var foo = {};
foo.bar = "Yes, this is a proper value!";
if (!!foo.bar) {
// member is set, do something
}
some easier and short options depending on the specific use case:
to check if the property exists, regardless of value, use the in operator ("a" in b)
to check a property value from a variable, use bracket notation (obj[v])
to check a property value as truthy, use optional
chaining (?.)
to check a property value boolean, use double-not / bang-bang / (!!)
to set a default value for null / undefined check, use nullish coalescing operator (??)
to set a default value for falsey value check, use short-circuit logical OR operator (||)
run the code snippet to see results:
let obj1 = {prop:undefined};
console.log(1,"prop" in obj1);
console.log(1,obj1?.prop);
let obj2 = undefined;
//console.log(2,"prop" in obj2); would throw because obj2 undefined
console.log(2,"prop" in (obj2 ?? {}))
console.log(2,obj2?.prop);
let obj3 = {prop:false};
console.log(3,"prop" in obj3);
console.log(3,!!obj3?.prop);
let obj4 = {prop:null};
let look = "prop"
console.log(4,"prop" in obj4);
console.log(4,obj4?.[look]);
let obj5 = {prop:true};
console.log(5,"prop" in obj5);
console.log(5,obj5?.prop === true);
let obj6 = {otherProp:true};
look = "otherProp"
console.log(6,"prop" in obj6);
console.log(6,obj6.look); //should have used bracket notation
let obj7 = {prop:""};
console.log(7,"prop" in obj7);
console.log(7,obj7?.prop || "empty");
I see very few instances where hasOwn is used properly, especially given its inheritance issues
There is a method, "hasOwnProperty", that exists on an object, but it's not recommended to call this method directly, because it might be sometimes that the object is null or some property exist on the object like: { hasOwnProperty: false }
So a better way would be:
// Good
var obj = {"bar": "here bar desc"}
console.log(Object.prototype.hasOwnProperty.call(obj, "bar"));
// Best
const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
console.log(has.call(obj, "bar"));
An ECMAScript 6 solution with reflection. Create a wrapper like:
/**
Gets an argument from array or object.
The possible outcome:
- If the key exists the value is returned.
- If no key exists the default value is returned.
- If no default value is specified an empty string is returned.
#param obj The object or array to be searched.
#param key The name of the property or key.
#param defVal Optional default version of the command-line parameter [default ""]
#return The default value in case of an error else the found parameter.
*/
function getSafeReflectArg( obj, key, defVal) {
"use strict";
var retVal = (typeof defVal === 'undefined' ? "" : defVal);
if ( Reflect.has( obj, key) ) {
return Reflect.get( obj, key);
}
return retVal;
} // getSafeReflectArg
Showing how to use this answer
const object= {key1: 'data', key2: 'data2'};
Object.keys(object).includes('key1') //returns true
We can use indexOf as well, I prefer includes
You need to use the method object.hasOwnProperty(property). It returns true if the object has the property and false if the object doesn't.
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true
console.log(object1.hasOwnProperty('toString'));
// expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false
Know more
Don't over-complicate things when you can do:
var isProperty = (objectname.keyname || "") ? true : false;
It Is simple and clear for most cases...
A Better approach for iterating on object's own properties:
If you want to iterate on object's properties without using hasOwnProperty() check,
use for(let key of Object.keys(stud)){} method:
for(let key of Object.keys(stud)){
console.log(key); // will only log object's Own properties
}
full Example and comparison with for-in with hasOwnProperty()
function Student() {
this.name = "nitin";
}
Student.prototype = {
grade: 'A'
}
let stud = new Student();
// for-in approach
for(let key in stud){
if(stud.hasOwnProperty(key)){
console.log(key); // only outputs "name"
}
}
//Object.keys() approach
for(let key of Object.keys(stud)){
console.log(key);
}

Categories

Resources