Skip to content
Advertisement

editing a JSON in JS and putting it in an array

so I have the following 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
}
}

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.

Answer

Something like this might work:

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}}`;
const data = JSON.parse(json);

const processed = Object.entries(data)
  .filter(([, { available }]) => available > 0)
  .map(([asset, { available, btcValue }]) => {
    return { asset, available, btcValue };
  });

const asArray = processed.map(Object.values);

console.table(processed);
console.log(asArray);

Object.entries returns an array of key-value pairs. Since it’s an array, you can:

  • call filter method to only keep items where available 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.

Advertisement