Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash map and pick

given an array

var test = [{a:1, b:2, c:3}, {a:4, b:5, c:6}, {a:7, b:8, c:9}]

how do I get an array of new objects like [{b:2, c:3}, {b:5, c:6}, {b:8, c:9}] with lodash?

I have tried _.map(test, _pick(???, ['b', 'c'])} What should I put in ??? ?

like image 298
Sean Avatar asked Feb 21 '17 16:02

Sean


People also ask

What is pick in Lodash?

pick() method is used to return a copy of the object that is composed of the picked object properties. Syntax: _.pick( object, paths ) Parameters: This method accepts two parameters as mentioned above and described below: object: This parameter holds the source object.

What is _ get?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])

How do I compare two arrays in Lodash?

isEqual() Method. The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.


1 Answers

You need to pass function to map and with ES6 you can use arrow function like this.

var test = [{a:1, b:2, c:3}, {a:4, b:5, c:6}, {a:7, b:8, c:9}]

var result = _.map(test, e => _.pick(e, ['b', 'c']))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
like image 150
Nenad Vracar Avatar answered Oct 03 '22 13:10

Nenad Vracar