Function get

  • Retrieves a value from an object using the specified path.

    Type Parameters

    • T extends object

      The type of the source object.

    • K

      The type of the default value.

    Parameters

    • obj: T

      The source object.

    • path: string

      The path to retrieve the value from the object. The path is specified as a dot-separated string.

    • defaultValue: K

      The default value to return if the path is not found or the value is undefined.

    Returns K | undefined

    The value found within the object based on the path, or the default value if the path is not found or results in an undefined value.

    // Example 1: Accessing a nested property
    const data = { user: { name: 'Alice', age: 25 } };
    console.log(get(data, 'user.name', 'Unknown')); // Output: 'Alice'
    // Example 2: Handling a missing property
    const data = { user: { name: 'Alice', age: 25 } };
    console.log(get(data, 'user.gender', 'Not specified')); // Output: 'Not specified'
    // Example 3: Accessing a deeply nested property
    const config = { server: { db: { host: 'localhost', port: 5432 } } };
    console.log(get(config, 'server.db.port', 3306)); // Output: 5432
    // Example 4: Using an invalid path
    const data = { user: { name: 'Alice' } };
    console.log(get(data, 'user.details.hobbies', [])); // Output: []