javascript – How to get specific information inside a Json with Node.JS?

Question:

{
"pair": "BTCBRL",
"bids": [
    [2257.89, 0.20752212, 90852987],
    [2257.88, 1.01201126, 90800395],
    [2249.98, 0.05052466, 90806289]
],
"asks": [
    [2272.14, 2.3648572, 90803493],
    [2279.63, 0.08722052, 90840584],
    [2279.75, 0.04118941, 90823262]
]
}

I have a function in my code that returns this JSON, I would like to get only the first bids and asks values, that is, the values ​​(2257.89, 2257.88, among others), how to proceed?

In this case, this JSON calls orderbook, so if I get orderbook.bids, it returns like this:

[
[2257.89, 0.20752212, 90852987],
[2257.88, 1.01201126, 90800395],
[2249.98, 0.05052466, 90806289]
],

but actually I just want the values ​​2257.89, 2257.88 and 2249.98!

Answer:

You can use Array#Map to only map the first item of each array :

var obj = {
  "pair": "BTCBRL",
  "bids": [
    [2257.89, 0.20752212, 90852987],
    [2257.88, 1.01201126, 90800395],
    [2249.98, 0.05052466, 90806289]
  ],
  "asks": [
    [2272.14, 2.3648572, 90803493],
    [2279.63, 0.08722052, 90840584],
    [2279.75, 0.04118941, 90823262]
  ]
};

var novoObj = Object.assign({}, obj);

['bids', 'asks'].forEach(function(item,i) {
  novoObj[item] = novoObj[item].map(a => a[0]);
});

console.log(novoObj);
.as-console-wrapper {
  top: 0;
  max-height: 100%!important
}
Scroll to Top