Home > Enterprise >  Using Axios to parse JSON objects containing only values without keys
Using Axios to parse JSON objects containing only values without keys

Time:08-10

I am trying to parse this json into two separate arrays

{"2022-08-11":11561.71,"2022-08-12":11396.5433,"2022-08-13":10875.3483,"2022-08-14":10036.1867,"2022-08-15":10307.895,"2022-08-16":10358.7683,"2022-08-17":10220.6033,"2022-08-18":10321.7317,"2022-08-19":10924.965,"2022-08-20":10776.9083,"2022-08-21":10133.3483}


currently I managed to get the object using axios on Vue, however I am struggling to seperate the strings of dates from the integer values in the arrDate and arrValue empty arrays

data: () => ({
    arrDate: [],
    arrValue: [],
    totalVuePackages: null

  }),
  created(){
 axios.get("https://api.coindesk.com/v1/bpi/historical/close.json?start=2019-01-01&end=2019-12-31").then(
      response => this.totalVuePackages = response.data);
 }
}


CodePudding user response:

If you want to put the keys in one array and the values in another, use the following

// your Axios response
const response = {data:{"2022-08-11":11561.71,"2022-08-12":11396.5433,"2022-08-13":10875.3483,"2022-08-14":10036.1867,"2022-08-15":10307.895,"2022-08-16":10358.7683,"2022-08-17":10220.6033,"2022-08-18":10321.7317,"2022-08-19":10924.965,"2022-08-20":10776.9083,"2022-08-21":10133.3483}};

// Reduce the entries (key / value pairs) into two separate arrays
const [dates, numbers] = Object.entries(response.data).reduce(
  ([keys, values], [key, value]) => [
    [...keys, key],
    [...values, value],
  ],
  [[], []]
);

console.log("dates", dates);
console.log("numbers", numbers);

// then assign to your Vue data with
// this.arrDate = dates;
// this.arrValue = numbers;
.as-console-wrapper { max-height: 100% !important; }

CodePudding user response:

You can simply use Object functions :

this.arrDate = Object.keys(response.data)
this.arrValue = Object.values(response.data)
  • Related