Sean
Sean

Reputation: 981

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 ??? ?

Upvotes: 7

Views: 12382

Answers (5)

Anselmo Park
Anselmo Park

Reputation: 1011

_.partialRight() can be used for trial of @Sean, such as _.map(test, _pick(???, ['b', 'c']))

_.map(test, _.partialRight(_.pick, ['b', 'c']));

// result: [ { b: 2, c: 3 }, { b: 5, c: 6 }, { b: 8, c: 9 } ]

Upvotes: 0

rab
rab

Reputation: 4144

It's not related to question asked, this can be easily done by ES6.

test.map(({ b, c }) => { 
  return { b, c }
});

Upvotes: 10

zieglar
zieglar

Reputation: 830

_.chain(test).map(function(e){return _.pick(e, ['b','c'])}).value();

Upvotes: 0

DJ Forth
DJ Forth

Reputation: 1518

You don't need to use lodash if you don't want too, if your using babel(es6) you can use deconstruction to solve the issue

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

let newList = test.map(({b, c})=>{
 return {b,c}
});

document.body.append(JSON.stringify(newList));

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122047

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>

Upvotes: 12

Related Questions