【问题标题】:Show JSON in VUE.js在 VUE.js 中显示 JSON
【发布时间】:2022-11-16 14:55:22
【问题描述】:

我在 Node.js 上制作了一个 API,如果我发送一些参数我会得到响应,它是同一个人但不同的语言信息,我想像第二个例子中那样展示它我一直无法弄清楚。

我如何获取数据

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

我多么想看到它

[
   {
        "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);
     }, 
    }
}

我现在怎么看[1]:https://i.stack.imgur.com/ezHgH.png

【问题讨论】:

  • how I want to see it - 您是否尝试将传入数据更改为您需要的数据?注意:您的“我想如何看待它”不太有效
  • 另外,“我是如何获取数据的”……它是否总是一个数组,每个对象都具有相同的Id
  • 是的,我尝试了 group_concat,但我将所有数据放在一列中,然后我不得不用 js 拆分它,但我就是无法解决。
  • I tried group_concat那到底是什么?
  • 是的,它返回同一个人,相同的 ID,只是不同的语言信息

标签: javascript mysql node.js vue.js


【解决方案1】:

而不是毫无意义地尝试在 MySQL 结果中获取您想要的格式(不可能) - 使用 JSON 将其转换为您想要的格式

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

工作示例

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-29
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 2021-02-28
    • 2020-03-24
    相关资源
    最近更新 更多