Search code examples
javascriptlodashunderscore.jsmarionette

is there a function to do this


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


Solution

  • 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();