I would like to achieve something like _.first with _.filter, that is, having a collection of elements, I’d like to get the first one (if exists) that matches a truth test (iterator). For example, given an array like the following: I would like to getthe first (and only first) element that matches my custom function: So far: Is there a
Tag: underscore.js
Merge two objects and overwrite the values if conflict
I’m trying to merge two objects and overwrite the values in the process. Is it possible with underscore to do the following? (I’m fine with not using underscore I just want it to be simple) Answer You could use Underscore’s extend: The first argument is modified, so if you don’t want to modify obj1 or obj2 just pass in {}.
Find by key deep in a nested array
Let’s say I have an object: I want to find the one object where the id is 1. Is there a function for something like this? I could use Underscore’s _.filter method, but I would have to start at the top and filter down. Answer Recursion is your friend. I updated the function to account for property arrays: updated jsFiddle:
Convert returned JSON Object Properties to (lower first) camelCase
I have JSON returned from an API like so: To keep this consistent with my code style (camelCase – lower case first letter) I want to transform the array to produce the following: What’s the easiest/best way to do this? Create a new Contact object and iterate over all the contacts in the returned array? or can I map the
Is there any way to rename js object keys using underscore.js
I need to convert a js object to another object for passing onto a server post where the names of the keys differ for example needs to turn into where I have lookup obj available for mapping all the keys Is there a function available in underscore.js or jQuery that I can use that does this functionality? thanks Answer As