Home > OS >  Show JSON in VUE.js
Show JSON in VUE.js

Time:11-17

I made an API on Node.js, If I send some params I get the response, it's the same person but different language info, I would like to present it like in the second example I haven't been able to figure it out.

How I'm getting the data

[
    {
        "Id": 1,
        "ced": "123",
        "Name": "Andres",
        "NativeLanguage": 1,
        "Level": 100,
        "NameLang": "spanish",
    },
    {
        "Id": 1,
        "ced": "123",
        "Name": "Andres",
        "NativeLanguage": 1,
        "Level": 100,
        "NameLang": "english",
    }
]

how I want to see it

[
   {
        "Id": 1,
        "ced": "123",
        "Name": "Andres",
   }
   "Idiomas":
     [
       {
         "NativeLanguage": 1,
        "Level": 100,
        "NameLang": "spanish",
       },
       {
         "NativeLanguage": 1,
        "Level": 100,
        "NameLang": "spanish",
       }

     ]

]
export default {
  el: "myFormPerson",
  data() {
    return {
      results:[],
      ced:'',
    }
  },
  methods: {
     submitForm() {
         axios.get('http://localhost:8080/person/'   this.ced)
        .then((response) => {
          this.results = response.data;
         //console.log(this.results);
         })
        .catch(function (error) {
        console.log(error);
        })
        .finally(function () {
        });
        //console.log(this.ced);
     }, 
    }
}

How I see it right now [1]: https://i.stack.imgur.com/ezHgH.png

CodePudding user response:

Rather than pointlessly trying to get the format you want in the MySQL result (not possible) - work with the JSON to convert it to what you want

this.results=Object.values(response.data.reduce((acc,{Id,ced,Name,...rest})=>(acc[Id]||={Id,ced,Name,Idiomas:[]},acc[Id].Idiomas.push({...rest}),acc),{}));

working example

const have = [{
    "Id": 1,
    "ced": "123",
    "Name": "Andres",
    "NativeLanguage": 1,
    "Level": 100,
    "NameLang": "spanish",
  },
  {
    "Id": 1,
    "ced": "123",
    "Name": "Andres",
    "NativeLanguage": 1,
    "Level": 100,
    "NameLang": "english",
  }
];
const want = Object.values(have.reduce((acc,{Id,ced,Name,...rest}) => (acc[Id]||={Id,ced,Name,Idiomas:[]},acc[Id].Idiomas.push({...rest}),acc),{}));

console.log(want);

  • Related