[Vuejs]-Correct way how to get and show data from specific JSON from API

0👍

Here the function that you can use to retrieve data that you need from the response:

function getData(data) {
  const out = {};

  data.forEach((items) => {
    Object.keys(items).forEach((key) => {
      out[key] = items[key].data;
    });
  });

  return out;
}
this.userInfo = getData(response.data.data) //usage of function

0👍

Alternative could be to simplify the object during parsing and reduce the resulting array to object :

var json = '{"data":[{"username":{"id":17,"data":"JohnDoe","created_at":"2019-05-09 15:52:23"}},{"phone":{"id":2,"data":"+123456789","created_at":"2019-05-08 17:31:52"}}]}'

var arr = JSON.parse(json, (k, v) => v.data || v)

var obj = arr.reduce((o, v) => Object.assign(o, v), {})

console.log(obj)
console.log(arr)

or, without reduce :

var obj = {}, json = '{"data":[{"username":{"id":17,"data":"JohnDoe","created_at":"2019-05-09 15:52:23"}},{"phone":{"id":2,"data":"+123456789","created_at":"2019-05-08 17:31:52"}}]}'

JSON.parse(json, (k, v) => v.data && k ? (obj[k] = v.data) : v)

console.log(obj)

Leave a comment