简化嵌套Json中的每个函数

时间:2019-06-10 03:18:48

标签: svelte

我已经嵌套了JSON数组

let car = [
{
    name: "BMW",
    detail: [
        {name: headlight, type: flame},
        {name: taillight, type: spark},
    ],
},
{
    name: "Merced Benz",
    detail: [
        {name: headlight, type: spark},
        {name: taillight, type: flame},
    ],
},]

我打电话时显示汽车名称 {#each car as cars} <p>{cars.name}</p> {/each}

但是 当我致电{cars.detail}时,其节目[object Object] 和 当我致电{cars.detail.name}时,其节目Undefined

我想打电话给每个细节

请帮助我使用此功能,先谢谢您

1 个答案:

答案 0 :(得分:1)

由于detail是一个数组,因此您还必须在每个块中使用另一个块来进行迭代。

示例(REPL

<script>
  let cars = [
    {
      name: "BMW",
      detail: [
        { name: "headlight", type: "flame" },
        { name: "taillight", type: "spark" }
      ]
    },
    {
      name: "Mercedes-Benz",
      detail: [
        { name: "headlight", type: "spark" },
        { name: "taillight", type: "flame" }
      ]
    }
  ];
</script>

{#each cars as car}
  <div>{car.name}</div>
  {#each car.detail as detail}
    <div>{detail.name}: {detail.type}</div>
  {/each}
{/each}