idx: Optional Property Traversal Utility

3.0.3 · deprecated · verified Sun Apr 19

idx is a utility function designed for safely traversing deeply nested properties within JavaScript objects and arrays, where intermediate properties might be `null` or `undefined`. It provides a concise syntax for accessing values without throwing errors. The current stable version is 3.0.3. However, the `idx` package is officially deprecated and no longer maintained. Its primary use case has been superseded by the native JavaScript optional chaining operator (`?.`), introduced in ES2020. A key differentiator noted in its documentation is that `idx` returns the `null` or `undefined` intermediate value if encountered, whereas optional chaining resolves to `undefined`. This library also strictly requires a Babel plugin (`babel-plugin-idx`) for correct transformation and optimal performance, as the runtime function is illustrative and not meant for direct execution. The library does not follow a regular release cadence due to its deprecated status.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core functionality of `idx` for safely accessing deeply nested properties in objects and arrays, showcasing how it handles `null` or `undefined` intermediate values compared to native optional chaining. It defines sample types and then uses `idx` to extract values that might otherwise cause runtime errors.

import idx from 'idx';

type User = {
  id: string;
  name: string;
  friends?: Array<User | null | undefined>;
};

type Props = {
  user?: User | null;
};

const props: Props = {
  user: {
    id: '123',
    name: 'Alice',
    friends: [
      {
        id: '456',
        name: 'Bob',
        friends: [{
          id: '789',
          name: 'Charlie'
        }]
      },
      null
    ]
  }
};

// Safely get the name of the user
const userName = idx(props, _ => _.user.name);
console.log('User name:', userName); // Output: Alice

// Safely get the name of the first friend's first friend
const charlieName = idx(props, _ => _.user.friends[0].friends[0].name);
console.log("Charlie's name:", charlieName); // Output: Charlie

// Accessing a property that is null/undefined at an intermediate step
const nonExistentFriendName = idx(props, _ => _.user.friends[1].name);
console.log('Non-existent friend name:', nonExistentFriendName); // Output: null (idx returns the null/undefined value)

// Compare with optional chaining behavior for an equivalent case
const nonExistentFriendNameOptionalChaining = props.user?.friends?.[1]?.name;
console.log('Non-existent friend name (optional chaining):', nonExistentFriendNameOptionalChaining); // Output: undefined

const deeplyNested = idx(props, _ => _.user.friends[0].friends[0].name);
console.log('Deeply nested:', deeplyNested); // Output: Charlie

view raw JSON →