用键排序对象(JS)

时间:2017-08-24 15:56:20

标签: javascript object

有对象。看起来像这样

enter image description here

需要对它进行排序,结果:mo,tu,we,th,fr,st,su

尝试这样做但不能正常工作

const sortOrder = {'mo': 1, 'tu': 2, 'we': 3, 'th':4,'fr':5, 'sa':6, 'su':7}
      const res = result.map(o => Object.assign({}, ...Object.keys(o).sort((a, b) => sortOrder[a] - sortOrder[b]).map(x => { return { [x]: o[x]}})))

1 个答案:

答案 0 :(得分:4)

复杂化。更容易:

var days = ["mo","tu","we","th","fr","sa","su"];

result.sort((a,b)=> days.indexOf(a.day) - days.indexOf(b.day));