tjmehta / object-loops

Functional methods like forEach, map, filter, and other Array methods for Objects in javascript
MIT License
33 stars 6 forks source link

Values map #27

Open rstacruz opened 7 years ago

rstacruz commented 7 years ago

It'd be nice to have a version of .map that will always return an array instead of an object. Very useful for JSX.

const listMap = require('object-keys/list-map')

people = {
  john: "John Lennon",
  ringo: "Ringo Starr"
}

<div>
  {listMap(people, name => `Mr. ${name}`)}
</div>

I can send you a PR, but I don't know what to name this function!

tjmehta commented 7 years ago

Does this work for you?

const values = require('object-loops/values')

people = {
  john: "John Lennon",
  ringo: "Ringo Starr"
}

<div>
  {values(people).map(name => `Mr. ${name}`)}
</div>
rstacruz commented 7 years ago

Yeah, that's what I've been doing, or rather:

values(map(people, (name, key) => /*...*/))

Would be nice to have it be done in one step in an optimized, though :)

tjmehta commented 7 years ago

What about a lazy version of chain?

const lazy = require('object-loops/lazy')

people = {
  john: "John Lennon",
  ringo: "Ringo Starr"
}

{lazy(people).values().map(name => Mr. ${name}`).toJSON()}
tjmehta commented 7 years ago

We could implement this by keeping track of all methods called then compute them all in one reduce (When toJSON is called)

tjmehta commented 7 years ago

I would like to avoid a creating a "values map" in object loops, bc then it would only make sense to create them all ("values forEach", "values reduce", etc). Let me know if lazy works for you I am happy to implement it this weekend if you are (or you can PR it 🙂)

rstacruz commented 7 years ago

Oh hey. :) So I think I gave a bad use case here, and bad naming. values(obj).map(...) is not sufficient because it discards the keys.

What I'm looking for is a way to do this:

people = {
  john: "John Lennon",
  ringo: "Ringo Starr"
}

<div>
  {listMap(people, (name, id) => <li id={id}>Mr. ${name}</li>)}
</div>

So in this case, values(obj).map(...) would be discarding that info. What would actually be useful is a map() that returns an array instead of an object.

bc then it would only make sense to create them all ("values forEach", "values reduce", etc)

That said, the only functions it makes sense on are:

forEach doesn't return anything. reduce returns the result of the reduction. Two functions seems very workable :)