JavaScript: How can I get all the keys and values of an object that begin with a specific string?

Learn javascript: how can i get all the keys and values of an object that begin with a specific string? with practical examples, diagrams, and best practices. Covers javascript development techniqu...

JavaScript: Efficiently Extracting Object Keys and Values by Prefix

Hero image for JavaScript: How can I get all the keys and values of an object that begin with a specific string?

Learn various JavaScript techniques to filter object properties and retrieve their keys and values based on a specific string prefix, enhancing data manipulation in your applications.

Working with JavaScript objects often involves manipulating their properties. A common requirement is to extract only those keys and their corresponding values that start with a particular string. This can be useful for filtering configuration settings, processing API responses, or organizing data based on naming conventions. This article explores several robust methods to achieve this, from traditional loops to modern array methods, providing practical examples and performance considerations.

Understanding the Core Problem

Before diving into solutions, let's visualize the problem. We have an object, and we want to iterate through its properties, check if each key begins with a specific prefix, and if it does, include that key-value pair in our result. The output should ideally be a new object containing only the filtered properties.

flowchart TD
    A[Start] --> B{Input Object & Prefix};
    B --> C{Get Object Keys};
    C --> D{Loop Through Keys};
    D --> E{Key Starts With Prefix?};
    E -- Yes --> F[Add Key-Value to Result];
    E -- No --> G[Skip Key];
    F --> D;
    G --> D;
    D -- All Keys Processed --> H[Return Result Object];
    H --> I[End];

Flowchart illustrating the process of filtering object keys by a specific prefix.

Method 1: Using for...in Loop with hasOwnProperty

The for...in loop is a classic way to iterate over enumerable properties of an object. It's crucial to use hasOwnProperty() to ensure you're only processing the object's own properties and not those inherited from its prototype chain. This method is straightforward and widely compatible.

function getKeysAndValuesByPrefixForIn(obj, prefix) {
  const result = {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key) && key.startsWith(prefix)) {
      result[key] = obj[key];
    }
  }
  return result;
}

const myObject = {
  'user_name': 'Alice',
  'user_email': 'alice@example.com',
  'admin_id': 123,
  'admin_role': 'super_admin',
  'temp_data': 'discard'
};

const userDetails = getKeysAndValuesByPrefixForIn(myObject, 'user_');
console.log(userDetails); // { user_name: 'Alice', user_email: 'alice@example.com' }

const adminDetails = getKeysAndValuesByPrefixForIn(myObject, 'admin_');
console.log(adminDetails); // { admin_id: 123, admin_role: 'super_admin' }

Method 2: Using Object.keys() with filter() and reduce()

Modern JavaScript offers more functional approaches. By combining Object.keys() to get an array of keys, filter() to select keys matching the prefix, and reduce() to construct a new object, we can achieve a more concise and declarative solution. This method is generally preferred for its readability and immutability.

function getKeysAndValuesByPrefixFunctional(obj, prefix) {
  return Object.keys(obj)
    .filter(key => key.startsWith(prefix))
    .reduce((acc, key) => {
      acc[key] = obj[key];
      return acc;
    }, {});
}

const myObject = {
  'user_name': 'Alice',
  'user_email': 'alice@example.com',
  'admin_id': 123,
  'admin_role': 'super_admin',
  'temp_data': 'discard'
};

const userDetails = getKeysAndValuesByPrefixFunctional(myObject, 'user_');
console.log(userDetails); // { user_name: 'Alice', user_email: 'alice@example.com' }

const adminDetails = getKeysAndValuesByPrefixFunctional(myObject, 'admin_');
console.log(adminDetails); // { admin_id: 123, admin_role: 'super_admin' }

Method 3: Using Object.entries() with filter() and fromEntries()

For an even more direct and often cleaner approach, Object.entries() allows you to work with key-value pairs directly as an array of [key, value] tuples. You can then filter() these entries and reconstruct an object using Object.fromEntries(). This method is particularly elegant for transformations involving both keys and values.

function getKeysAndValuesByPrefixEntries(obj, prefix) {
  return Object.fromEntries(
    Object.entries(obj).filter(([key, value]) => key.startsWith(prefix))
  );
}

const myObject = {
  'user_name': 'Alice',
  'user_email': 'alice@example.com',
  'admin_id': 123,
  'admin_role': 'super_admin',
  'temp_data': 'discard'
};

const userDetails = getKeysAndValuesByPrefixEntries(myObject, 'user_');
console.log(userDetails); // { user_name: 'Alice', user_email: 'alice@example.com' }

const adminDetails = getKeysAndValuesByPrefixEntries(myObject, 'admin_');
console.log(adminDetails); // { admin_id: 123, admin_role: 'super_admin' }

Performance Considerations

While all methods achieve the desired outcome, their performance characteristics can vary, especially with very large objects. Generally, the for...in loop tends to be slightly faster in some benchmarks because it avoids the overhead of creating intermediate arrays. However, for most typical use cases, the performance difference is negligible, and readability often takes precedence. For extremely performance-critical applications, benchmarking with your specific data set is recommended.

Hero image for JavaScript: How can I get all the keys and values of an object that begin with a specific string?

Relative performance comparison of different methods for filtering object properties.