简体   繁体   English

如何使用多列对 json 进行排序

[英]how to sort json with multiple columns

I'm working with BootstrapVue .我正在使用BootstrapVue

I have a json which is structured like this (called json in the complete question)我有一个结构如下的 json(在完整问题中称为json

[
    {"ID": "1", "Name": "Harry", "Age": "18"},
    {"ID": "2", "Name": "Ron", "Age": "18"},
    {"ID": "3", "Name": "Hermione", "Age": "18"},
    {"ID": "4", "Name": "Ginny", "Age": "18"},
    {"ID": "5", "Name": "Fred", "Age": "18"},
]

In my template I show it like following in my <b-form-select> :在我的模板中,我在<b-form-select>中显示如下:

<b-form-select class="showPointer">
  <option v-for="item in json" :key="item.id">
    ID: {{ item.id}}, Name: {{ item.name}}, Age: {{ item.age}}
  </option>
</b-form-select>

Now to my problem : I want to sort it based on my name and I know that I have to put it first into a computed-function but I don't know how..现在我的问题:我想根据我的name对它进行sort ,我知道我必须首先将它放入computed-function ,但我不知道如何..

But I want to display it in my template like in my example above (ID, than Name, than Age).但我想在我的template中显示它,就像我上面的例子一样(ID,比名字,比年龄)。

Thanks for your help!谢谢你的帮助! Thank You!谢谢你!

You don't need computed for this.您不需要为此计算。

You could sort it immediately after you receive the request response.您可以在收到请求响应后立即对其进行排序。

Example例子

get(....).then(response=> { 
    this.json = response.sort((a,b) => a.name - b.name)
})

Abregre is right, you don't need computed for this. Abregre 是对的,您不需要为此计算。

But in any case, you can use computed like this:但无论如何,您可以像这样使用计算:

<option v-for="item in sortedJson" :key="item.id">

computed: {
  sortedJson () {
    return this.json.sort((a, b) => a.Name - b.Name)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM