【问题标题】:sort the Json data According to timestamp in Vuejs根据Vuejs中的时间戳对Json数据进行排序
【发布时间】:2020-04-15 14:03:54
【问题描述】:

我正在使用 api 渲染一个 Json

new window.Vue({
el: '#containerwrapper',
data() {
return {
bannerData:""
}
},
created() {
axios.get('http://localhost:8080/pi.json')
.then(response => {
this.bannerData = response.data;
});
},
})

这给了我如下的 Json 数据

[
  {
    "id": 118,
    "title": "Feuerwerk",
    "location": "MUC",
    "pressInformation": [
      {
        "id": 215,
        "tstamp": "1577110478",
        "created": "2019-09-10T12:13:53+02:00",
        "title": "Chemi215",
        "teaser": "",
        "subline": "Ursachenforschung dauert"
        }
    ]
  },
  {
    "id": 144,
    "title": "Testing Stage",
    "location": "BER",
    "pressInformation": [
      {
        "id": 254,
        "tstamp": "1576838212",
        "created": "2019-11-27T13:47:31+01:00",
        "title": "Chemi254",
        "teaser": "",
        "subline": ""
        },
      {
        "id": 250,
        "tstamp": "1576838221",
        "created": "2019-12-09T12:36:36+01:00",
        "title": "Chemi250",
        "teaser": "",
        "subline": ""
        }
    ]
  }
]

我在我的模板中渲染数据如下

<div v-for="(eventTitle, i) in bannerData">
    <div v-for="(title,index) in eventTitle.pressInformation" :key="title.id">
        <div id="pressTimeStamp">{{title.created}} Uhr</div>
        <div id="pressTitleTitle">{{title.title}}</div>
        <div id="pressTitle">
        <h2>{{eventTitle.title}}</h2>
        <div id="pressSubline">{{title.subline}}</div>
    </div>
</div>

输出如我所料。有人可以建议我,如何编写一个方法以便整理我的输出取决于“创建”时间戳

【问题讨论】:

标签: javascript vue.js vuejs2 vuejs3


【解决方案1】:
new window.Vue({
el: '#containerwrapper',
data() {
return {
bannerData:""
}
},
created() {
axios.get('http://localhost:8080/pi.json')
.then(response => {
response.data.pressInformation.sort(function(a, b){return b['tstamp']-a['tstamp']}));
this.bannerData = response.data;
});
},
})

【讨论】:

  • 我确实收到错误:未捕获(承诺中)类型错误:无法读取未定义的属性“排序”
【解决方案2】:

您可以将sort 方法与回调函数一起使用。

从您的数据看来,您已经有了以秒为单位的时间戳。使用它很容易进行排序。

例如你可以这样写:

arr.sort(function(a, b) {
  return +a.pressInformation.tstamp - +b.pressInformation.tstamp;
});

如果你写a-b表示升序,而b-a是降序。

这里使用额外的+ 符号将字符串转换为int。

文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

【讨论】:

  • 谢谢,但是这个函数没有返回排序数组response.data.sort(function(a, b){ return +a.pressInformation.tstamp - +b.pressInformation.tstamp}); 我猜,pressInformation.tstamp 是未定义的,因为 pressInformation 是一个对象数组。
猜你喜欢
  • 1970-01-01
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
  • 2013-06-06
  • 2012-07-15
  • 2018-08-09
相关资源
最近更新 更多