Reference article · Programming
JavaScript: arrays, objects and data transformations
A catalogue stores several records. An array represents an ordered collection; each object groups an item’s properties. This combination appears in API responses and tables.
Lists and properties
Array indexes start at zero; items[0] is the first item. length gives its length. Objects group named properties, accessed with a dot or brackets. A missing property returns undefined.
const items = [
{ name: "HTML", available: true },
{ name: "CSS", available: false },
{ name: "JavaScript", available: true },
];
console.log(items[0].name); // HTMLFilter, transform and find
filter creates an array of matching items. map creates an array of transformed results. find returns the first match or undefined. Each receives a function describing the operation.
const available = items.filter((item) => item.available); const names = available.map((item) => item.name); const css = items.find((item) => item.name === "CSS"); console.log(names); // ["HTML", "JavaScript"] console.log(css?.available); // false
Mutation and shared references
const prevents reassignment but does not make arrays or objects immutable. push changes its original array. filter and map return new arrays, but contained objects can still share references with the originals.
Shallow copies
Object spread copies properties, not nested objects recursively. The edited record below is new; the original name remains unchanged.
const edited = { ...items[0], name: "Basic HTML" };
console.log(edited.name); // Basic HTML
console.log(items[0].name); // HTMLCases to check
- Filter an empty list; expect an empty array.
- Search for a missing name and check the result before reading its properties.
- Add a fourth record and predict the filtered names.
References
Related articles
- Fundamentals: variables, conditions and loops
- Semantic HTML and page structure
- CSS: box model, Flexbox and Grid
- JavaScript: functions, parameters and scope
- DOM and events: connect JavaScript to HTML
- Promises, async/await and fetch requests
- HTTP and web APIs: requests, responses and status codes
- JSON: format, parsing and data validation
- Git: changes, commits, branches and remotes
- Node.js and npm: project scripts and dependencies
- Debugging and tests: finding and checking errors
- Colour formats: HEX, RGB and HSL
- UUID identifiers
- Random values in JavaScript
