Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte Each function in Nested Json

Tags:

svelte

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

like image 646
Collin Chu Avatar asked Dec 31 '25 03:12

Collin Chu


1 Answers

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}
like image 50
Tholle Avatar answered Jan 04 '26 18:01

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!