How to pick up a specific piece of information within a Json with Node.JS?

Asked

Viewed 851 times

3

{
"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 in my code a function that returns this JSON, I would like to take only the first values of bids and asks, ie the values (2257.89, 2257.88, among others), how to proceed?

In this case, this JSON calls orderbook, so if I catch orderbook.bids, it returns this way:

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

but I really only want 2257.89, 2257.88 and 2249.98!

1 answer

2

You can use Array#Map to map only 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
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.