EzDevInfo.com

lodash

A JavaScript utility library delivering consistency, modularity, performance, & extras. lodash a javascript utility library delivering consistency, modularity, performance, & extras.

Remove key from object/value using lodash

I am trying to end up with 2 arrays of objects, a & b. If the key 'name' appears in array a, I do not want it to appear in b.

var characters = [
  { 'name': 'barney', 'blocked': 'a', 'employer': 'slate' },
  { 'name': 'fred', 'blocked': 'a', 'employer': 'slate' },
  { 'name': 'pebbles', 'blocked': 'a', 'employer': 'na' },
  { 'name': 'pebbles', 'blocked': 'b', 'employer': 'hanna' },
  { 'name': 'wilma', 'blocked': 'c', 'employer': 'barbera' },
  { 'name': 'bam bam', 'blocked': 'c', 'employer': 'barbera' }
];
var a = _.filter(characters, { 'blocked': 'a' });
var z = _.pluck(a,'name');
var b = _.difference(characters, a);
_(z).forEach(function (n) {

    //_.pull(b, _.filter(b, { 'name': n }));
    //b = _.without(b, { 'name': n });
    // b = _.without(b, _.filter(b, { 'name': n }));
    _.without(b, _.filter(b, { 'name': n }));
});

The code runs, but array "b" is never altered. What I expect is for array "b" to have the two objects with the names wilma and bam bam. I tried doing it without a loop.

var c = _.without(b, _.filter(b, { 'name': 'pebbles' }));
var d = _.without(b, { 'name': 'pebbles' });
var f = _.pull(b, { 'name': 'pebbles' });

though the code executes, pebbles will not go.


Source: (StackOverflow)

Underscore.js findWhere nested objects

I have an object of folders/files that looks like this:

{
  about.html : {
    path : './about.html'
  },
  about2.html : {
    path : './about2.html'
  },
  about3.html : {
    path : './about3.html'
  },
  folderName : {
    path : './folderName',
    children : {
      sub-child.html : {
        path : 'folderName/sub-child.html'
      }
    }
  }
}

And it can go 6-7 levels deep of folders having children.

I want to find the object where path is equal to a string that I provide. Regardless of how deep it is.

I'm using underscore which only does top level:

_.findWhere(files,{path:'./about2.html'}

How can I do a deep, nested search. Does underscore have something for this or do I need to build a mixin with recursion?


Source: (StackOverflow)

Advertisements

Lodash - How to get multiple results

I am using lodash. I like it.

I have a users array which looks like this:

var users = [{
    'user': 'barney',
    'age': 36,
    'active': true
}, {
    'user': 'fred',
    'age': 40,
    'active': false
}, {
    'user': 'pebbles',
    'age': 1,
    'active': true
}];

Here's how I'm finding the first user and plucking the user property:

_.result(_.find(users, 'active', false), 'user');
// 'fred'

However, I wanted to pluck the user and the age values. How can I write this?


Source: (StackOverflow)

Using Lo-Dash and Underscore simulatenously in RequireJS environment

In a RequireJS environment, what's the best way to allow some AMD modules to use Lo-Dash while others simultaneously use Underscore?


Source: (StackOverflow)

Chaining pluck() and flatten() with lodash

This works, but how can I chain it?...

allWeeks = _.flatten(_.pluck(dates.months, 'weeks'))
allDays  = _.flatten(_.pluck(allWeeks, 'days'))

I've tried:

allDays = _.chain(dates.months).pluck('weeks').flatten().pluck('days').flatten()

And this:

allDays = _(dates.months).pluck('weeks').flatten().pluck('days').flatten()

Source: (StackOverflow)

transform object to array with lodash

How i can transform big object to array with lodash?

example:

var obj = {
    22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[],}
    12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[],}
}
// transform to 
var arr = [{name:"John", id:22...},{name:"Ivan", id:12...}]

Thanks!


Source: (StackOverflow)

lodash multi-column sortBy descending

There's a nifty method to sort an array of object based on several propertes:

var data = _.sortBy(array_of_objects, ['type', 'name']);

However that is only for ascending sorting. Is there some handy way of defining direction per column? E.g.

var data = _.sortBy(array_of_objects, [{'type': 'asc'}, {'name': 'desc'}]);

Source: (StackOverflow)

Lo-Dash, difference between array and collection

A glance at the Lo-Dash docs shows that the API falls in to categories of:

  1. Arrays,
  2. Chaining,
  3. Collections,
  4. Functions,
  5. Objects,
  6. Utilities,
  7. Methods,
  8. and Properties

A more detailed look in to the Arrays API shows approximately 30 different methods available that are applicable to arrays.

The Collections API has a few more methods than the Arrays API, and they do not share the same methods.

Within the Collections API, a collection is described as an object that is iterated, and may be an array:

collection (Array|Object|string): The collection to iterate over.

Also, interestingly, there's a Collections API method _.toArray that returns an array from a collection:

Arguments

collection (Array|Object|string): The collection to convert. Returns

(Array): Returns the new converted array.

Would anyone happen to know a formal difference between an array and collection in the Lo-Dash API? I was under the presumption it was a difference due to Backbone.js, however, am now questioning my reasoning to that end, since the methods may be available elsewhere. Thanks in advance.


Source: (StackOverflow)

Is it possible to add non html comment in underscore.js or lodash templates?

Is it possible to add non html comments in underscore.js or lodash ?

Something like :

<%-- We do this here because... %>

So that the comment is not in the resulting generated html code ?

If I write :

<!-- We do this here because... -->

The comment is in the resulting html.

Thank you.


Source: (StackOverflow)

Flatten array with objects into 1 object

Given input:

[{ a: 1 }, { b: 2 }, { c: 3 }]

How to return:

{ a: 1, b: 2, c: 3 }

For arrays it's not a problem with lodash but here we have array of objects.


Source: (StackOverflow)

Backbone / Underscore chain method with where method

There has to be something simple I am missing here.

http://jsfiddle.net/v9mdZ/

I am just learning Backbone and Underscore/loDash and am trying to get familiar with chain.

I have the following code, which works as expected:

var ids = _.pluck(collection.where({'is_checked':true}), 'id');

I attempted to refactor this, using chain like so:

var ids = collection.chain().where({'is_checked':true}).pluck('id').value();

Why doesn't the refactored code work? Am I using chain wrong?

Solution (details below)

Don't use where with chain.


Source: (StackOverflow)

Lodash: Constructing single object from many - Merging/overriding properties

Note: I filed this question under lodash as I'm pretty sure it can help me solve that problem nicely, but haven't put my finger on it just now

I have an object describing different user roles and their permissions;

I will have something like 10-15 roles defined "like this" (this doesn't reflect the application code but the problem itself):

    var role1 = {
    views: {
        v1: {access: true},
        v2: {access: false},
        v#: {access: false}
    }
}

var role2 = {
    views: {
        v1: {access: false},
        v2: {access: true},
        v3: {access: true},
    }
}

The user connected will have multiple roles; In that example it could be ['role1', 'role2'], and out of this I need to construct a single permissions object that will be a combination of all the props defined in all the user roles.

It is basically whitelist-based, where all "true" properties should override anything that was defined as false. Thus, the expected result should be:

permissions = {
    views: {
        v1: {access: true},
        v2: {access: true},
        v2: {access: true}
    }
}

I'm not too sure how to tackle that one without relying on crazy nested loops

Here's a starting point in JSBin: http://jsbin.com/usaQejOJ/1/edit?js,console

Thanks for your help!


Source: (StackOverflow)

Creating a .net like dictionary object in Javascript

I want to create a object in JavaScript which will store values in key, value pair and I should be able to pass some key and should be able to get its value back. In .NET world we can use dictionary class for this kind of implementation. Do we have any option in JavaScript world? I am using ExtJs 4.1, so if you know of any option in ExtJS even that would work.

I have tried something like this but I cannot get value by key.

var Widget = function(k, v) {
    this.key = k;
    this.value = v;
};

var widgets = [
    new Widget(35, 312),
    new Widget(52, 32)
];

Source: (StackOverflow)

How can I use lodash/underscore to sort by multiple nested fields?

I want to do something like this:

var data = [
    {
        sortData: {a: 'a', b: 2}
    },
    {
        sortData: {a: 'a', b: 1}
    },
    {
        sortData: {a: 'b', b: 5}
    },
    {
        sortData: {a: 'a', b: 3}
    }
];

data = _.sortBy(data, ["sortData.a", "sortData.b"]);

_.map(data, function(element) {console.log(element.sortData.a + " " + element.sortData.b);});

And have it output this:

"a 1"
"a 2"
"a 3"
"b 5"

Unfortunately, this doesn't work and the array remains sorted in its original form. This would work if the fields weren't nested inside the sortData. How can I use lodash/underscore to sort an array of objects by more than one nested field?

I've turned this into a lodash feature request: https://github.com/lodash/lodash/issues/581


Source: (StackOverflow)

Why is lodash.each faster than native forEach?

I was trying to find the fastest way of running a for loop with its own scope. The three methods I compared were:

var a = "t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t".split();

// lodash .each -> 1,294,971 ops/sec
lodash.each(a, function(item) { cb(item); });

// native .forEach -> 398,167 ops/sec
a.forEach(function(item) { cb(item); });

// native for -> 1,140,382 ops/sec
var lambda = function(item) { cb(item); };
for (var ix = 0, len = a.length; ix < len; ix++) {
  lambda(a[ix]);
}

This is on Chrome 29 on OS X. You can run the tests yourself here:

http://jsperf.com/lo-dash-each-vs-native-foreach/13

How is lodash's .each almost twice as fast as native .forEach? And moreover, how is it faster than the plain for? Sorcery? Black magic?


Source: (StackOverflow)