Reputation: 55
I'm using node-binance-api to pull some Binance balance data. The API call returns all of the currencies, and I want to filter it to only include those where I have a balance.
Code:
await binance.balance((error, balances) => {
if ( error ) return console.error(error);
console.log(balances);
var filtered = _.filter(balances, function(b) {return b.available > 0})
console.log(filtered);
});
The first console.log
returns all data as expected:
RENBTC: { available: '0.00000000', onOrder: '0.00000000' },
SLP: { available: '0.00000000', onOrder: '0.00000000' },
STRAX: { available: '0.00000000', onOrder: '0.00000000' },
...
I expected the second console.log
to return the coin name and the balance, but it's only returning the balances:
[
{ available: '0.03993250', onOrder: '0.00000000' },
{ available: '8.11227680', onOrder: '0.00000000' }
]
How can I get the coin symbol to be included after filtering?
Upvotes: 1
Views: 150
Reputation: 1175
If you still want to get an array of the following type, you can use reduce
[
{
"available": "0.03993250",
"key": "XXX",
"onOrder": "0.00000000"
},
{
"available": "8.11227680",
"key": "YYY",
"onOrder": "0.00000000"
}
]
const balances = {
RENBTC: {
available: '0.00000000',
onOrder: '0.00000000'
},
SLP: {
available: '0.00000000',
onOrder: '0.00000000'
},
STRAX: {
available: '0.00000000',
onOrder: '0.00000000'
},
XXX: {
available: '0.03993250',
onOrder: '0.00000000'
},
YYY: {
available: '8.11227680',
onOrder: '0.00000000'
}
};
const filtered = Object.entries(balances).reduce((acc, [key, value]) => {
const available = value.available
if (available <= 0) {
return acc
}
acc.push({
available,
key,
onOrder: value.onOrder
})
return acc
}, [])
console.log("Result", filtered);
Upvotes: 0
Reputation: 28563
Lodash's _.filter
, even when passed an object, returns an array.
Iterates over elements of collection, returning an array of all elements predicate returns truthy for.
If you want an object of the same format but "filtered" one way would be to iterate over the keys of the object, test that properties value, then assign or not to a new object.
const balances = {
RENBTC: { available: '0.00000000', onOrder: '0.00000000' },
SLP: { available: '0.00000000', onOrder: '0.00000000' },
STRAX: { available: '0.00000000', onOrder: '0.00000000' },
XXX: { available: '0.03993250', onOrder: '0.00000000' },
YYY: { available: '8.11227680', onOrder: '0.00000000' }
};
const filtered = {};
for (const k of Object.keys(balances)) {
if (balances[k].available > 0) {
filtered[k] = balances[k];
}
}
console.dir(filtered);
An alternate way would be to delete the properties you don't want in the object, but this would be destructive if you don't copy the object first.
Upvotes: 1