【发布时间】:2018-07-10 11:01:49
【问题描述】:
我知道我的问题标题可能会令人困惑(我知道对象属性没有顺序),因为我已经提出了解决方案,所以为了避免创建 XY problem,让我先解释一下我的目标:
我需要呈现 N 个按字长分组的单词表,并且(这是棘手的事情)按长度降序排列。比如:
Words with length 4
===================
abcd | other fields
abce | other fields
abcf | other fields
Words with length 3
===================
abc | other fields
abd | other fields
abe | other fields
Words with length 2
===================
...
我从一个没有任何分组的 API 获取我的单词列表,所以我现在正在做的是:
let grouped = {};
// Assume words is an Array of words of multiple lengths
words.forEach(w => {
if (typeof grouped[w.length] === 'undefined')
grouped[w.length] = [];
grouped[w.length].push({'word': w});
// Pushing an object cause of other calculated and not rellevant fields
});
当然,当我渲染这个 grouped 单词时(我使用的是 Vue.js)...
<WordsTable
v-for="(group, length) in grouped"
:words="group"
:word-length="length"
/>
我使用 word-length 属性来渲染表格的标题长度为 N 的单词。
一切正常,但我按升序顺序获得表格(而且,我再次意识到这可能是巧合,因为对象中没有顺序)。所以真正的问题是,谁能想出办法让 Vue 用降序键迭代我的 grouped 对象?
注意:可能没有特定长度的单词,所以Object.keys(grouped) 可能是[3,4,7,9,10]
更新:
评论者建议对grouped 使用数组而不是对象。我已经尝试过了,确实可能会稍微好一点,但并不能完全解决问题。
如果grouped是一个数组,我可以反转它:
<WordsTable
v-for="(group, length) in grouped.reverse()"
...
/>
但在这种情况下,索引会丢失,不能再用于呈现表格的标题。
【问题讨论】:
-
您可以将单词存储在数组而不是对象中。将
let grouped = {}替换为let grouped = [] -
我试过了。也不行。让我用更多信息更新我的问题。
标签: javascript vue.js vuejs2 javascript-objects