Home > database >  Svelte select specific object data from JSON
Svelte select specific object data from JSON

Time:07-14

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.

CodePudding user response:

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.

  • Related