What is for-in?
The 'for-in' npm package is a utility that allows you to iterate over the properties of an object in JavaScript. It provides a simple and efficient way to loop through object keys, even for objects that inherit properties from their prototype.
What are for-in's main functionalities?
Iterating over object properties
This feature allows you to loop through each property of an object. The function provided to forIn is called with each property's value and key. This is particularly useful for objects with enumerable properties.
const forIn = require('for-in');
const object = {a: 1, b: 2, c: 3};
forIn(object, function(value, key) {
console.log(key + ': ' + value);
});
Other packages similar to for-in
lodash.foreach
Lodash's forEach method is similar to for-in but offers more extensive functionality, such as iterating over arrays, objects, and other collection types. It also supports exiting the iteration early by returning false, which is not supported by for-in.
object.entries
This is not an npm package but a built-in JavaScript method that returns an array of a given object's own enumerable string-keyed property [key, value] pairs. This can be used in combination with forEach for similar functionality to for-in but requires conversion to an array first.
for-in
Iterate over the own and inherited enumerable properties of an object, and return an object with properties that evaluate to true from the callback. Exit early by returning false
. JavaScript/Node.js
Install
Install with npm:
$ npm install --save for-in
Usage
var forIn = require('for-in');
var obj = {a: 'foo', b: 'bar', c: 'baz'};
var values = [];
var keys = [];
forIn(obj, function (value, key, o) {
keys.push(key);
values.push(value);
});
console.log(keys);
console.log(values);
About
Related projects
- arr-flatten: Recursively flatten an array or arrays. This is the fastest implementation of array flatten. | homepage
- collection-map: Returns an array of mapped values from an array or object. | homepage
- for-own: Iterate over the own enumerable properties of an object, and return an object with properties… more | homepage
Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Contributors
Building docs
(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)
To generate the readme, run the following command:
$ npm install -g verbose/verb
Running tests
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
$ npm install && npm test
Author
Jon Schlinkert
License
Copyright © 2017, Jon Schlinkert.
Released under the MIT License.
This file was generated by verb-generate-readme, v0.4.2, on February 28, 2017.