0

I would like to use lodash function chaining in order to iterate over an array of objects, and push each of the object values into a new array.

I could use a nested forEach for that purpose but I understand there are better ways.

I want to turn this array from:

[ {a: 'foo', b: 'bar'}, {a: 'baz', b: 'foo2'}, {a: 'bar2', b: 'baz2'} ] 

into the following result:

[ 'foo','bar','baz', 'foo2', 'bar2', 'baz2' ] 

Can anyone please help?

4
  • 1
    _.flatMap(Object.values)? Commented Feb 22, 2018 at 10:17
  • It is a builtin JavaScript function. Gets an array of the values in an object. Object.values Commented Feb 22, 2018 at 10:20
  • 1
    Wonderful ! Thanks Commented Feb 22, 2018 at 10:21
  • 2
    Array.prototype.flatMap should be in the next version of JavaScript so you would just write: myObjects.flatMap(Object.values); Commented Feb 22, 2018 at 10:22

2 Answers 2

1

Based upon Aluan Haddad's comment, I came up with the following solution:

 const theArray = [ {a: 'foo', b: 'bar'}, {a: 'baz', b: 'foo2'}, {a: 'bar2', b: 'baz2'} ]; _(theArray) .flatMap(Object.values) 
Sign up to request clarification or add additional context in comments.

Comments

1

Just for fun, here is how to do this without lodash

theArray.reduce( (acc,item) => acc.concat(Object.values(item)) , [] ) 

For those into recycling and watching their weight

const concatWith = (fn,a,b) => a.concat(fn(b)) theArray.reduce( concatWith.bind(null,Object.values) , [] ) 

Or just use a curry function

const curry = (fn, ...args) => fn.length <= args.length ? fn(...args) : curry.bind(null, fn, ...args) 

and do it this way

const concatWith = curry( (fn,a,b) => a.concat(fn(b)) ) theArray.reduce( concatWith(Object.values) , [] ) 

Enjoy!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.