is there a function to do this

175 Views Asked by At

I'm looking for a way to get the same functionality of the Lodash _.forIn() Method but without using Lodash. I can use Underscore however.

This is what the method does https://www.geeksforgeeks.org/lodash-_-forin-method/?ref=gcse

2

There are 2 best solutions below

4
Julian On BEST ANSWER

A basic recipe for _.forIn was given in a comment by @VLAZ:

function forIn(collection, iteratee) {
    for (var key in collection) {
        iteratee(collection[key], key, collection);
    }
    // return the collection to uphold Underscore convention
    return collection;
}

// using the above to output the contents of an object
forIn({a: 1, b: 2, c: 3}, console.log);
// 1 a {a: 1, b: 2, c: 3}
// 2 b {a: 1, b: 2, c: 3}
// 3 c {a: 1, b: 2, c: 3}

All the iteratee shorthand niceness can be added by taking the iteratee through _.iteratee first:

import _ from 'underscore';

function forIn(collection, iteratee, context) {
    // turn shorthands into functions
    iteratee = _.iteratee(iteratee, context);
    for (var key in collection) {
        iteratee(collection[key], key, collection);
    }
    return collection;
}

To add it to the Underscore namespace, so you can use it in chaining and OOP notation, use _.mixin:

import { mixin } from 'underscore';

mixin({forIn});

// now you can do things like this:
_.chain(someObject)
.forIn(someFunction)
.sortBy(someProperty)
.andSoForth();
1
svarog On

Just pass your object to underscore's _.map (if you want the result to be an array), _.mapObject (if you want the result to be an object) or _.each functions and access the keys

_.map({a: 1, b: 2, c: 3}, (item, key, collection) => console.log(key))
> a
> b
> c