英文:
how do you create a grouped rows table in svelte?
问题
以下是您要翻译的代码部分:
svelte模板伪代码
{#each cities as city}
{#if city.name != currentCity}
{@const currentCity = city.name}
<tr><th colspan="5" scope="colgroup">{currentCity}</th></tr>
{/if}
<tr><td>{city.person} - ({city.jobTitle})</td></tr>
{/each}
英文:
I am trying to group my table rows to look like this with svelte. The svelte template code below is not working.
svelte template pseudocode
{#each cities as city}
{#if city.name != currentCity}
{@const currentCity = city.name}
<tr><th colspan="5" scope="colgroup">{currentCity}</th></tr>
{/if}
<tr><td>{city.person} - ({city.jobTitle})</td></tr>
{/each}
答案1
得分: 3
最好的方法是对数据进行预处理,将其分组,类似以下的操作可以实现:
const grouped = data.reduce((acc, cur) => {
if (!acc[cur.city]) acc[cur.city] = [];
acc[cur.city].push(cur);
return acc;
}, {});
这将创建一个以城市为键,以该城市中所有人员数组为值的对象。
然后,你可以使用 Object.entries
来循环遍历这些键,以及使用内部循环来渲染所有的人员:
{#each Object.entries(grouped) as [city, people]}
<tr>
<td colspan="5" scope="colgroup">{city}</td>
</tr>
{#each people as person}
<tr>
<td>{person.name}</td>
<td>{person.role}</td>
</tr>
{/each}
{/each}
其中的一个好处是,即使人员未按城市排序(比如,如果你有 Edinburgh、London、Edinburgh),它仍将正确地对人员进行分组。
英文:
The best way is to preprocess the data to split it along the groups,
Something like this could do
const grouped = data.reduce((acc, cur) => {
if (!acc[cur.city]) acc[cur.city] = []
acc[cur.city].push(cur)
return acc
}, {})
This will make an object with the cities as keys and an array of all the people in this city as the value for the key.
Then you can use Object.entries
to loop over those keys and with an inner loop render all the people:
{#each Object.entries(grouped) as [city, people]}
<tr>
<td colspan="5" scope="colgroup">{city}</td>
</tr>
{#each people as person}
<tr>
<td>{person.name}</td>
<td>{person.role}</td>
</tr>
{/each}
{/each}
One benefit of this is that it will still group the people correct even if they are not sorted by city (like if you with Edinburgh, London, Edinburgh)
答案2
得分: 0
不要尝试在模板内部更改状态,这是不应该的。以一种功能性的方式或提前设置数据。
例如,在cities
上运行reduce
以创建组,并在组上进行迭代,或者如果您想要迭代分组,请在脚本中执行此操作并将其存储在一个单独的变量中。
英文:
Do not try to mutate state within the template, it is not supposed to. Set up data in a functional way or ahead of time.
I.e. run a reduce
on cities
to create groups and iterate over the groups or, if you want to do the grouping iteratively, do so in the script and store it in a separate variable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论