【问题标题】:Sort all arrays in object using javascript/typescript使用 javascript/typescript 对对象中的所有数组进行排序
【发布时间】:2017-05-24 21:49:30
【问题描述】:

我想对这个对象中的每个数组进行排序,目前我是这样做的

this.userInfo = {
    Interests: [],
    Websites: [],
    Games: [],
    Locations: [],
    Companies: [],
    Projects: [],
    Schools: [],
    Studies: []
};


this.userInfo.Interests.sort();
this.userInfo.Websites.sort();
this.userInfo.Games.sort();
this.userInfo.Locations.sort();
this.userInfo.Companies.sort();
this.userInfo.Projects.sort();
this.userInfo.Schools.sort();
this.userInfo.Studies.sort();

还有其他更优雅的方式吗?

【问题讨论】:

  • 做一个 for(var prop in this.userInfo) this.userInfo[prop].sort();

标签: javascript arrays sorting typescript


【解决方案1】:

使用Object.keys获取所有数组自己的属性名,然后使用Array#forEach迭代键:

Object.keys(this.userInfo).forEach(function(key) {
  this.userInfo[key].sort(function(a, b) {
    // your sorting logic
  });
});

【讨论】:

    【解决方案2】:

    试试这个对你有帮助,

    this.userInfo = {
      Interests: [2, 3, 4, 1],
      Websites: [2, 3, 4, 1],
      Games: [2, 3, 4, 1],
      Locations: [2, 3, 4, 1],
      Companies: [2, 3, 4, 1],
      Projects: [2, 3, 4, 1],
      Schools: [2, 3, 4, 1],
      Studies: [2, 3, 4, 1]
    };
    
    for (var i in this.userInfo) {
      console.log(this.userInfo[i].sort());
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-17
      • 2017-02-07
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多