Dynamically extract a value within an object based on its key

Table of Contents

  • Use Case
  • Required Steps
    1. Create a “filter” object
    2. Intersect keys between objects
    3. Extract the value

Use Case

We sometimes deal with a case where we have an object or associative array, and we want to extract a value inside the object by its key. In addition, we have the key as a value in the root entity. Let’s see the below sample data.

{
  "sku": "ABC-003",
  "inventory": {
    "ABC-001": 12,
    "ABC-002": 0,
    "ABC-003": 97,
    "ABC-004": 23
  }
}

In the above data, we want to get the inventory of a product, whose SKU is defined dynamically in the sku property. If the SKU is static, for example ABC-003, we could just “hardcode” the SKU in a JMESPath syntax, such as below.

&{inventory."ABC-003"}

However, it is a different case. In this case, the SKU is dynamic.

Required Steps

Create a “filter” object

Firstly, we should create an object that contains a key that matches the SKU in the sku property. We can use a Value Setter to achieve this.

The above transformer will give us the below data as a result.

{
  "sku": "ABC-003",
  "inventory": {
    "ABC-001": 12,
    "ABC-002": 0,
    "ABC-003": 97,
    "ABC-004": 23
  },
  "filter": {
    "ABC-003": true
  }
}

Intersect keys between objects

Now, we can find the intersection keys between the objects inventory and filter using Operator Transformer in order to get the inventory object filtered.

The result of the above transformer is below.

{
  "sku": "ABC-003",
  "inventory": {
    "ABC-003": 97
  },
  "filter": {
    "ABC-003": true
  }
}

Extract the value

Since an associative array or object cannot have duplicated keys, the inventory object should have one remaining key as a result of the key intersection. The final step to extract the value is by using Copy using a pattern, such as below.

The property result will now hold the value of the inventory.ABC-003, which is 97.

{
  "sku": "ABC-003",
  "inventory": {
    "ABC-003": 97
  },
  "filter": {
    "ABC-003": true
  },
  "result": 97
}
2 Likes

this is cool, thank you for this.

2 Likes