Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

94
Vistas
Svelte select specific object data from JSON

I need help accessing specific objects in a JSON file based on a name value in Svelte.

I am using JSON as a data source and am able to pull it into my page and loop through it with each.

The JSON looks like so:


[
    {
      "id": 1,
      "title": "Project 1",
      "body": "Project 1 text"
    },
    {
      "id": 2,
      "title": "Project 2",
      "body": "Project 2 text"
    }
  ]

I access the JSON like this:

<script context="module">
    export const load = async ({ fetch }) => {
        const res = await fetch("https://amarton.github.io/amcom-portfolio-svelte/static/port.json");
        const projects = await res.json();
        return {
            props: {
                projects,
            }
        }
    }
 
</script>

<script>
    export let projects; 
</script>

And then loop through and display it like this:

       {#each projects as project}
            <h2>{project.title}</h2>
            <p>{project.body}</p>
        {/each}

I'd like to be able to access objects based on my assigned ids. For example, how do I grab JUST the object with the id of 2 and display its title and body in my page?

Sorry if this is a very basic question and thanks for much for any help you can provide.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You would not use {#each} and instead get the item in the JS. E.g. like this:

$: project = projects.find(p => p.id == '2');

You now can reference project as is without the loop.

If you want a dynamic selection you can bind a select element to an ID like this:

<script>
    export let projects = [];

    let id = '';
    $: project = projects.find(p => p.id == id);
</script>

<label>
    Project
    <select bind:value={id}>
        <option />
        {#each projects as p}
            <option value={p.id} label={p.title} />
        {/each}
    </select>
</label>

{#if project}
    <h2>{project.title}</h2>
    <p>{project.body}</p>
{/if}

REPL

The reactive statement ($:) ensures that project is updated if projects or id changes.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda