點燈坊

失くすものさえない今が強くなるチャンスよ

Using toPairs to Get Key and Value from Object

Sam Xiao's Avatar 2021-11-21

If we want to get key and value from Object simultaneously, we used to use keys to get all keys, and then use [] with the key to get value. Now we can use toPairs to get key and value at once.

Version

Ramda 0.27.1

keys

import { pipe, keys, map } from 'ramda'

let data = {
  title: 'FP in JavaScript',
  price: 100
}

pipe (
  keys,
  map (k => {
    let v = data [k]
    return `${k}:${v}`
  })
) (data) // ?
  • keys : get all keys from the Object
  • data [k] : get value from key

toparis000

toPairs

import { pipe, toPairs, map } from 'ramda'

let data = {
  title: 'FP in JavaScript',
  price: 100
}

pipe (
  toPairs,
  map (([k, v]) => `${k}:${v}`)
) (data) // ?
  • toPairs : get all keys and values at once
  • map (([k, v]) => {}) : destructure key and value, no need to use [] to get value

toPairs
{k: v} -> [[k, v]...]
Get key and value from the Object and return Nested Array

toparis000

Conclusion

  • toPairs is identical to ES2017’s Object.entries

Reference

Ramda, toPairs