javascript - Vuejs _.orderBy 没有对 json 进行排序

标签 javascript vue.js vuejs2 lodash

更新 以下是我使用 axios 通过 API 获取的 json。

 bannerData= [
        {
          "id": 118,
          "title": "Geruchsbel\u00e4stigung",
          "location": "DOR",
          "pressInformation": [
            {
                "id": 257,
                "title": "Chemi257"
              },
              {
               "id": 256,
               "title": "Chemi256",
              }
          ]
        },
        {
          "id": 144,
          "title": "Testing Stage",
          "location": "LEV",
          "pressInformation": [
            {
              "id": 254,
               "title": "Chemi254",
            },
            {
              "id": 261,
               "title": "Chemi261",
            }
          ]
        }
      ]
computed: {
    orderedUsers: function() {
      this.secondSubBanner = [];
      for (let i = 0; i < this.bannerData.length; i++) {
        this.subBanner = this.bannerData[i].pressInformation;
        for (let j = 0; j < this.subBanner.length; j++) {
          this.secondSubBanner.push(this.subBanner[j].id);
          console.log(this.secondSubBanner); // output: 257, 256, 254,261
        }
      }
      return this.secondSubBanner;
    },
sortedArray() {
      let v = this.orderedUsers.sort();
      console.log(v); // output: 254, 256, 257, 261
      return _.orderBy(this.bannerData, v)
    }

sortedArray 使用 sort() 按顺序打印 ID。但它无法对 Json 属性进行排序,具体取决于使用 _.orderBy()。谁能说我哪里做错了?

最佳答案

试试这个算法。我想有了你想要的东西,你不需要 lodash。我只使用内置的 flatMap()sort() 来得到这个:

function sortedArray(bannerData) {
  const array = bannerData.flatMap(x => x.pressInformation)
  return array.sort( (a,b) => a.id - b.id )
}

bannerData = [
  {
    "id": 118,
    "title": "Geruchsbel\u00e4stigung",
    "location": "DOR",
    "pressInformation": [
      {
        "id": 257,
        "title": "Chemi257"
      },
      {
        "id": 256,
        "title": "Chemi256",
      }
    ]
  },
  {
    "id": 144,
    "title": "Testing Stage",
    "location": "LEV",
    "pressInformation": [
      {
        "id": 254,
        "title": "Chemi254",
      },
      {
        "id": 261,
        "title": "Chemi261",
      }
    ]
  }
]

console.log(sortedArray(bannerData))

关于javascript - Vuejs _.orderBy 没有对 json 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59457802/

相关文章:

javascript - $timeout scrollTop 指令在 angularJS 中不起作用

JavaScript 速度监控工具?

javascript - 将 v-model 与数组一起使用时,从 vue.js 收到无法读取未定义属性的错误

javascript - 如何在 Vue 中加载 YAML 文件?

javascript - Vue 组件回收导致 watch 意外起火

vuejs2 - VueJs + 元素 UI : How to set default value with photo el-select?

javascript - 使用 Greymonkey 循环遍历元素

vue.js - Vue.js单文件组件导入外部js库

json - Vue 使用 v-model 更改 key 本身

javascript - 在 javascript 或 bootstrap 中创建可点击的工具提示