Skip to content

Instantly share code, notes, and snippets.

@electerious
Last active January 24, 2017 09:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save electerious/75b46c66736c5c408bfe to your computer and use it in GitHub Desktop.
Save electerious/75b46c66736c5c408bfe to your computer and use it in GitHub Desktop.
forEach for Objects, Arrays and NodeLists
const each = (data, fn) => {
if (data==null) return false
if ((data).constructor===Object) return Array.prototype.forEach.call(Object.keys(data), (key) => fn(data[key], key, data))
else return Array.prototype.forEach.call(data, (item, i) => fn(item, i, data))
}
@electerious
Copy link
Author

Examples:

// Array
each([0, 1, 2], (item, i, array) => console.log(item, i, array))

// NodeList
each(document.querySelectorAll('a'), (elem, i, array) => console.log(elem, i, nodelist))

// Object
each({ a: 1, b: 1, c: 1}, (item, key, obj) => console.log(item, i, obj))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment