How to remove undefined and null values from an object using lodash?

You can simply chain _.omit() with _.isUndefined and _.isNull compositions, and get the result with lazy evaluation. Demo var result = _(my_object).omit(_.isUndefined).omit(_.isNull).value(); Update March 14, 2016: As mentioned by dylants in the comment section, you should use the _.omitBy() function since it uses a predicate instead of a property. You should use this for lodash … Read more

Lodash create collection from duplicate object keys

Use _.groupBy and then _.map the resulting object to an array of objects. var newOutput = _(output) .groupBy(‘article’) .map(function(v, k){ return { article: k, titles: _.map(v, ‘title’) } }) .value(); var output = [{“article”:”BlahBlah”,”title”:”Another blah”},{“article”:”BlahBlah”,”title”:”Return of the blah”},{“article”:”BlahBlah2″,”title”:”The blah strikes back”},{“article”:”BlahBlah2″,”title”:”The blahfather”}]; let newOutput = _(output) .groupBy(‘article’) .map(function(v, k){ return { article: k, titles: _.map(v, … Read more

Filter nested array in object array by array of values

If you’re trying to filter the elements whose course IDs contain in the filter.courses, you may use Array#every and Array#includes to do that: const data = [{“guid”:”j5Dc9Z”,”courses”:[{“id”:3,”name”:”foo”}]},{“guid”:”a5gdfS”,”courses”:[{“id”:1,”name”:”bar”},{“id”:3,”name”:”foo”}]},{“guid”:”jHab6i”,”courses”:[{“id”:7,”name”:”foobar”}]}]; const courses = [1, 6, 3]; const r = data.filter(d => d.courses.every(c => courses.includes(c.id))); console.log(r);

Flatten array with objects into 1 object

Use Object.assign: let merged = Object.assign(…arr); // ES6 (2015) syntax var merged = Object.assign.apply(Object, arr); // ES5 syntax Note that Object.assign is not yet implemented in many environment and you might need to polyfill it (either with core-js, another polyfill or using the polyfill on MDN). You mentioned lodash, so it’s worth pointing out it … Read more

How to Import a Single Lodash Function?

You can install lodash.isequal as a single module without installing the whole lodash package like so: npm install –save lodash.isequal When using ECMAScript 5 and CommonJS modules, you then import it like this: var isEqual = require(‘lodash.isequal’); Using ES6 modules, this would be: import isEqual from ‘lodash.isequal’; And you can use it in your code: … Read more

Split JavaScript array in chunks using Lodash

Take a look at lodash’ chunk: https://lodash.com/docs#chunk const data = [“a1”, “a2”, “a3”, “a4”, “a5”, “a6”, “a7”, “a8”, “a9”, “a10”, “a11”, “a12”, “a13”]; const chunks = _.chunk(data, 3); console.log(chunks); // [ // [“a1”, “a2”, “a3”], // [“a4”, “a5”, “a6”], // [“a7”, “a8”, “a9”], // [“a10”, “a11”, “a12”], // [“a13″] // ] <script src=”https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js”></script>