Retrieves a value from an object, or an alternative object, falling to a back-up default value if not found.
The key is a string, which can be split based on the use of the period character.
For example:
const source = {
lives: 3,
render: {
screen: {
width: 1024
}
}
}
const lives = GetValue(source, 'lives', 1);
const width = GetValue(source, 'render.screen.width', 800);
const height = GetValue(source, 'render.screen.height', 600);
In the code above, lives
will be 3 because it's defined at the top level of source
.
The width
value will be 1024 because it can be found inside the render.screen
object.
The height
value will be 600, the default value, because it is missing from the render.screen
object.
name | type | arguments | description |
---|---|---|---|
source | object |
The primary object to try to retrieve the value from. If not found in here, |
|
key | string |
The name of the property to retrieve from the object. If a property is nested, the names of its preceding properties should be separated by a dot ( |
|
defaultValue | * |
The value to return if the |
|
altSource | object | <optional> |
An alternative object to retrieve the value from. If the property exists in |
The value of the requested key.