Introduction to get-value
The get-value
function is an essential tool in modern JavaScript programming, allowing developers to safely access deep values within objects. This comprehensive guide will introduce you to the get-value
functionality and provide numerous API examples with code snippets to help you master its use.
Basic Usage
The basic usage of get-value
can be illustrated with the following example:
const getValue = require('get-value');
const obj = { a: { b: { c: 1 } } };
console.log(getValue(obj, 'a.b.c')); // Output: 1
Handling Undefined Values
You can handle cases where the property path does not exist by providing a default value:
const getValue = require('get-value');
const obj = { a: { b: { } } };
console.log(getValue(obj, 'a.b.c', 'defaultValue')); // Output: defaultValue
Accessing Array Elements
With get-value
, you can also access elements within arrays:
const getValue = require('get-value');
const obj = { a: [{ b: { c: 1 } }] };
console.log(getValue(obj, 'a.0.b.c')); // Output: 1
Custom Object Types
The get-value
function works with custom objects and types as well:
const getValue = require('get-value');
class CustomObject {
constructor() {
this.nest = { value: 42 };
}
}
const obj = new CustomObject();
console.log(getValue(obj, 'nest.value')); // Output: 42
Safe Object Access
Use get-value
to safely access deeply nested properties without fear of runtime errors:
const getValue = require('get-value');
const obj = { a: { b: null } };
console.log(getValue(obj, 'a.b.c', 'safe')); // Output: safe
App Example
Here’s a practical application of get-value
within an actual Node.js app:
const getValue = require('get-value');
const express = require('express');
const app = express();
const database = {
users: [
{ id: 1, profile: { name: 'Alice' } },
{ id: 2, profile: { name: 'Bob', meta: { age: 30 } } }
]
};
app.get('/user/:id', (req, res) => {
const userId = parseInt(req.params.id, 10);
const user = database.users.find(user => user.id === userId);
if (user) {
res.json({
name: getValue(user, 'profile.name', 'Unknown'),
age: getValue(user, 'profile.meta.age', 'Not specified')
});
} else {
res.status(404).send('User not found');
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this app, the use of get-value
allows for safe retrieval of deeply nested user profile data from a mock database, ensuring that the server does not crash due to missing properties.
Hash: 27e8a59339ceb857b8510cafb6fb7dc64897db7859dcc5f9121d85a93ce8a01a