javascript / beginner
Snippet
Finding a Specific Object in an Array Using the Find Method
The Array.prototype.find method searches through an array and returns the first element that satisfies the provided testing function. In Svelte, combining find with a reactive declaration ($:) ensures that the selected item is automatically recalculated whenever the target identifier or the underlying list changes.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>let items = [{ id: 1, name: 'Apple', inStock: false },{ id: 2, name: 'Banana', inStock: true },{ id: 3, name: 'Cherry', inStock: true }];let selectedId = 2;$: selectedItem = items.find(item => item.id === selectedId);</script><div>{#if selectedItem}<p>Selected: {selectedItem.name} ({selectedItem.inStock ? 'Available' : 'Out of Stock'})</p>{:else}<p>No item found.</p>{/if}</div>
svelte
Breakdown
1
let items = [
Declares an array of product objects containing identifiers, names, and stock flags.
2
$: selectedItem = items.find(item => item.id === selectedId);
Uses find to locate the single object matching selectedId and updates reactively whenever selectedId changes.
3
{#if selectedItem}
Checks whether a matching object was found before attempting to display its properties.