so I have the following json.
JavaScript
x
33
33
1
{
2
"BTC": {
3
"available": 0.00024868,
4
"onOrder": 0,
5
"btcValue": 0.00024868,
6
"btcTotal": 0.00024868
7
},
8
"LTC": {
9
"available": 0,
10
"onOrder": 0,
11
"btcValue": 0,
12
"btcTotal": 0
13
},
14
"ETH": {
15
"available": 0,
16
"onOrder": 0,
17
"btcValue": 0,
18
"btcTotal": 0
19
},
20
"NEO": {
21
"available": 0,
22
"onOrder": 0,
23
"btcValue": 0,
24
"btcTotal": 0
25
},
26
"BNB": {
27
"available": 0.08943066,
28
"onOrder": 0,
29
"btcValue": 0.0004663808919,
30
"btcTotal": 0.0004663808919
31
}
32
}
33
I need to remove the items that don’t have a value in the “available” field (such as NEO and ETH and set the result in an array. Then remove the onOrder and btcTotal fields.
such as:
BTC 0.00024868 0.00024868
BNB 0.8943066 0.0004663808919
I am writing my little project in JS on NodeJS as a little hobby project. But, so far all I am able to get right is listing the JSON in the console.
Advertisement
Answer
Something like this might work:
JavaScript
1
14
14
1
const json = `{"BTC":{"available":0.00024868,"onOrder":0,"btcValue":0.00024868,"btcTotal":0.00024868},"LTC":{"available":0,"onOrder":0,"btcValue":0,"btcTotal":0},"ETH":{"available":0,"onOrder":0,"btcValue":0,"btcTotal":0},"NEO":{"available":0,"onOrder":0,"btcValue":0,"btcTotal":0},"BNB":{"available":0.08943066,"onOrder":0,"btcValue":0.0004663808919,"btcTotal":0.0004663808919}}`;
2
const data = JSON.parse(json);
3
4
const processed = Object.entries(data)
5
.filter(([, { available }]) => available > 0)
6
.map(([asset, { available, btcValue }]) => {
7
return { asset, available, btcValue };
8
});
9
10
const asArray = processed.map(Object.values);
11
12
console.table(processed);
13
console.log(asArray);
14
Object.entries
returns an array of key-value pairs. Since it’s an array, you can:
- call
filter
method to only keep items whereavailable
was greater than 0 - call
map
method to transform the filtered array of key-value pairs into an array of objects (where each object has properties:asset
,available
,btcValue
)
You can get rid of asArray
if you want, if it’s not useful. It’s just to give you an idea of what’s possible.