點燈坊

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

Using Object.entries to Get Key and Value

Sam Xiao's Avatar 2021-11-21

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

Version

ECMAScript 2017

Object.keys

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

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

entries

Object.entries

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

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

entries001

Conclusion

  • Object.entries is more concise than the combination of Object.keys and []