Search code examples
svelte

Svelte Each function in Nested Json


I have nested JSON Array

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},
    ],
},]

it's show cars name when i call {#each car as cars} <p>{cars.name}</p> {/each}

but when i call {cars.detail} its show [object Object] and when i call {cars.detail.name} its show Undefined

i wanna call each name of detail

please help me to use this each function at svelte thank you before


Solution

  • Since detail is an array, you have to use another each block to iterate over that as well.

    Example (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}