如何在Svelte中创建分组行表格?

huangapple go评论40阅读模式
英文:

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中创建分组行表格?

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) =&gt; {
  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]}
  &lt;tr&gt;
    &lt;td colspan=&quot;5&quot; scope=&quot;colgroup&quot;&gt;{city}&lt;/td&gt;
  &lt;/tr&gt;
  {#each people as person}
	&lt;tr&gt;
      &lt;td&gt;{person.name}&lt;/td&gt;
	  &lt;td&gt;{person.role}&lt;/td&gt;
	&lt;/tr&gt;
  {/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.

huangapple
  • 本文由 发表于 2023年2月10日 04:58:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定