Home > Blockchain >  Return a new array from the data from json
Return a new array from the data from json

Time:09-24

Help to return a new array from the data from json. At the output I want to get array of itog

[12860498,20156554,19187309]

[
      {
        "0": {
          "itog": 12860498,
          "return": 1107294,
          "beznal": 10598131
        },
        "date": "2021-01-31"
      },
      {
        "0": {
          "itog": 20156554,
          "return": 1147363,
          "beznal": 18127393
        },
        "date": "2021-02-28"
      },
      {
        "0": {
          "itog": 19187309,
          "return": 1667656,
          "beznal": 17597434
        },
        "date": "2021-03-31"
      }
    ]

CodePudding user response:

const a = [
  {
    "0": {
      "itog": 12860498,
      "return": 1107294,
      "beznal": 10598131
    },
    "date": "2021-01-31"
  },
  {
    "0": {
      "itog": 20156554,
      "return": 1147363,
      "beznal": 18127393
    },
    "date": "2021-02-28"
  },
  {
    "0": {
      "itog": 19187309,
      "return": 1667656,
      "beznal": 17597434
    },
    "date": "2021-03-31"
  }
];

const result = a.map(function(i) {
  return i[0].itog;
});

console.log( result );

CodePudding user response:

You can use Array.map to get it.

var input = new Array({
    "0": {
      "itog": 12860498,
      "return": 1107294,
      "beznal": 10598131
    },
    "date": "2021-01-31"
  },
  {
    "0": {
      "itog": 20156554,
      "return": 1147363,
      "beznal": 18127393
    },
    "date": "2021-02-28"
  },
  {
    "0": {
      "itog": 19187309,
      "return": 1667656,
      "beznal": 17597434
    },
    "date": "2021-03-31"
  }
);

var output = input.map(item => item[0]['itog']);
console.log(output);

CodePudding user response:

Please accept one of the previous solutions, they are perfect for what you need.

A more generic solution could be:

const data = [
  {
    "0": {
      "itog": 12860498,
      "return": 1107294,
      "beznal": 10598131
    },
    "date": "2021-01-31"
  },
  {
    "0": {
      "itog": 20156554,
      "return": 1147363,
      "beznal": 18127393
    },
    "date": "2021-02-28"
  },
  {
    "0": {
      "itog": 19187309,
      "return": 1667656,
      "beznal": 17597434
    },
    "date": "2021-03-31"
  }
];

let itogs = [];
data.forEach(entry => {
  itogs = [
    ...itogs,
    ...Object.values(entry)
      .map(obj => obj['itog'])
      .filter(itog => itog)
  ];
});


console.log(itogs);

  • Related