简体   繁体   中英

Javascript/Ramda: How to make the following code functional

Hi I have the following object structure,

const usersList = {
  NFr9F4WbBxR4H5ajolbS6q0skPF2: {
    name: "justin davidson",
    uid: "NFr9F4WbBxR4H5ajolbS6q0skPF2"
  },
  asas9F4WbBxR4H5ajolbS6q0sasF2: {
    name: "sawyer davidson",
    uid: "asas9F4WbBxR4H5ajolbS6q0sasF2"
  }
}

It has a user ID as key, and it's user object nested within. I want to store the inner user data. I've been using Ramda JS and have done so by doing the following,

let x = []
const y = R.keys(usersList).forEach((uid) => {  
  x.push(usersList[uid])
  return x
})

which returns

[{"name":"justin davidson","uid":"NFr9F4WbBxR4H5ajolbS6q0skPF2"},    
{"name":"sawyer davidson","uid":"asas9F4WbBxR4H5ajolbS6q0sasF2"}]

..however I'd like achieve the same in a purely functional way. What would be the best approach here? I'm guessing compose and map but I can't seem to work it out. Looking for a little direction.

Thanks

Just use map instead of forEach :

const x = R.keys(usersList).map((uid) => usersList[uid])

It looks like there's also a values method that does what you want:

const x = R.values(usersList)

There isn't always a function tucked away in some lib that does exactly what you want it to do. Showing how to do things on your own demonstrates that you don't have to feel "stuck" when you're faced with a problem and you can't find a magical function to solve it for you. Once you learn the function exists, sure, go ahead and replace your home-brew solution with the built-in. But until then, don't be afraid to write code and move on.

 // ovalues :: (Object k:v) -> [v] const ovalues = o => Array.from(Object.keys(o), k => o[k]) const usersList = { NFr9F4WbBxR4H5ajolbS6q0skPF2: { name: "justin davidson", uid: "NFr9F4WbBxR4H5ajolbS6q0skPF2" }, asas9F4WbBxR4H5ajolbS6q0sasF2: { name: "sawyer davidson", uid: "asas9F4WbBxR4H5ajolbS6q0sasF2" } } console.log(ovalues(usersList)) 

So yep, R.values does exist in the Rambda library, but next time don't be afraid to try to solve it on your own. You have a powerful brain, now use it ^_^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM