Using Lodash Map with Objects
Lodash’s _.map method is designed to be used with arrays, but playing around with it I found a couple of uses with objects that I hope you will find useful.
Require Lodash in your Node server app or use import in your React front-end client app
const _ = require('lodash') // Nodeimport _ from 'lodash' // React
Given the object below return an array of object keys where the value is true.
let quote_state = { btc: true, usdt: false, eth: false }
If we were to use _.map as we do with an array we would NOT get the desired result.
const _quote_filter = _.map(quote_state, (val, key) => {
if (val) {
return key
}
})
console.log(_quote_filter) //=> [ 'btc', undefined, undefined ]
However, if we use _.map as an iteration block — similar to a loop — then we can use the val and key arguments to set conditions and push items onto an array.
const _quote_filter = []
_.map(quote_state, (val, key) => {
if (val) {
_quote_filter.push(key)
}
})
console.log(_quote_filter) //=> [ 'btc' ]
You can also achieve the above with _.each, however, you cannot use _.each in the example below where we want to map object keys onto their respective sub_object and return an array.
let markets = {
'BTC/USD': {
buys: 0,
sells: 3
},
'DASH/BTC': {
buys: 3,
sells: 1
},
'ETH/BTC': {
buys: 3,
sells: 2
}
}const _markets_arr = _.map(markets, (obj, key) => {
obj.symbol = key
return obj
})console.log(_markets_arr)
//=> [
{ buys: 0, sells: 3, symbol: 'BTC/USD' },
{ buys: 3, sells: 1, symbol: 'DASH/BTC' },
{ buys: 3, sells: 2, symbol: 'ETH/BTC' }
]
Although, if you need to set conditions and filter out objects you will need to use _.map as mentioned before.
const _markets_arr = []
_.map(markets, (val, key) => {
val.symbol = key
if (val.buys > 0) {
_markets_arr.push(val)
}
})
console.log(_markets_arr)
//=> [
{ buys: 3, sells: 1, symbol: 'DASH/BTC' },
{ buys: 3, sells: 2, symbol: 'ETH/BTC' }
]
You could use _.filter to do the same as above, HOWEVER, I have found both _.filter and vanilla JavaScript’s Array.prototype.filter do not work on certain JSON responses.
This is especially true when working with Elasticsearch queries called from a Node server and then fed to the front end via Socket.io.
As a bonus trick using _.each with an object — You can map an object key onto it’s respective sub-object whilst retaining the original object’s structure.
_.each(markets, (obj, key) => {
obj.symbol = key
})
console.log(markets)
//=> {
'BTC/USD': { buys: 0, sells: 3, symbol: 'BTC/USD' },
'DASH/BTC': { buys: 3, sells: 1, symbol: 'DASH/BTC' },
'ETH/BTC': { buys: 3, sells: 2, symbol: 'ETH/BTC' }
}