javascript / beginner
Snippet
Transforming Item Collections with the Array Map Method
The `Array.prototype.map()` method creates a brand-new array populated with the results of calling a provided callback function on every element in the calling array. In Svelte applications, transforming data into clean, derived structures before passing them to markup components helps maintain clear separation between data manipulation and rendering logic.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
const rawUsers = [{ id: 1, firstName: 'Ada', lastName: 'Lovelace' },{ id: 2, firstName: 'Alan', lastName: 'Turing' }];const formattedNames = rawUsers.map(user => ({id: user.id,fullName: `${user.firstName} ${user.lastName}`}));
svelte
Breakdown
1
const rawUsers = [ ... ];
Defines an initial array of user objects containing separate first and last name properties.
2
const formattedNames = rawUsers.map(user => ({
Iterates over each user element to construct and return a new transformed object.
3
id: user.id,
Preserves the unique identifier required for tracking items in UI list iterations.
4
fullName: `${user.firstName} ${user.lastName}`
Combines first and last name fields into a single unified display string using a template literal.
5
}));
Closes the mapping expression, producing an immutable new array of transformed objects.