for ... in
statements get enumerable keys from the whole prototype chain.
To prevent bugs, it is recommended to write loops like this:
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
// "key" is a property of "obj"
}
}
Pretty verbose, right?
This is a babel-plugin-macro which allows you to iterate only over own keys of an object when using for ... in
.
This module can be installed either with npm
or with yarn
, and should be installed as one of your project's devDependencies
:
npm install --save-dev for-own.macro
# or
yarn add --dev for-own.macro
Once you have configured babel-plugin-macros
you can import/requie import-all.macro
.
Here is an example:
import own from "for-own.macro";
for (const key in own(obj)) {
const value = obj[key];
}
// ↓ ↓ ↓ ↓ ↓ ↓
for (const key in obj) if (Object.hasOwnProperty.call(obj, key)) {
const value = obj[key];
}
The own
macro only works inside for ... in
loops. This code will throw an error at compile time:
const ownProps = own(obj);
MIT