Skip to content

Instantly share code, notes, and snippets.

@idkjs
Created June 16, 2021 15:14
Show Gist options
  • Save idkjs/35e3f7746544921621cb416828d60042 to your computer and use it in GitHub Desktop.
Save idkjs/35e3f7746544921621cb416828d60042 to your computer and use it in GitHub Desktop.
Checks if Javascript Object has some property
// let 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
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
%bs.raw
{|
function hasOwnProperty(object, property) {
try {
return (object.hasOwnProperty(property));
} catch {
return false;
}
}
|};
[@bs.val] external hasOwnProperty: ('a, 'b) => bool = "hasOwnProperty";
let hasOwnProperty = (~obj, ~property) =>
hasOwnProperty(obj, property);
[@bs.val]
external objAssign: (Js.t({..}), Js.t({..})) => Js.t({..}) =
"Object.assign";
let object1 = Js.Obj.empty();
let object1 = objAssign(object1, {"property1": 42});
Js.log(hasOwnProperty(~obj=object1, ~property="property1"));
// expected output: true
Js.log(hasOwnProperty(~obj=object1, ~property="toString"));
// expected output: false
Js.log(hasOwnProperty(~obj=object1, ~property="hasOwnProperty"));
// expected output: false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment