Node to get value by ID

I often work with data from APIs that is not formatted in an easy way for getting the information you want. Take this data for example:

fields: [
{ 
"id": "57",
"value": "example"
},
{
"id": "25"
"value": "Another example"
}
]

Say I need to get the value of field 25. If I copy the parameter path and put it in my expression, it will just grab the value of the second item from the list. But that order could change in the future, so it’s not helpful.

Because of this, my most-used code snippet in n8n is a snippet that helps me grab an item by key/value pair where the key and value are both siblings in the json structure.

Example:

function filterById(jsonObject, id, key = 'id', value='value') {
    try {
        var val = jsonObject.filter(jsonObject=>(jsonObject[key] == id))[0][value];
        return val?val:'';
    } catch (e) {
        return ''
    }
}

var jsonobject = //items array

var values= {};

values['field 25'] = filterById(jsonobject, '25');

return [{json: values}];

If we could get this functionality in a no-code node, that would be fantastic! The only way I’ve found to do this is to use the item list node + an if node, but that results in more work especially if I want multiple field values.

A perfect job for $jmespath. You can get your field value with this expression:
{{ $jmespath($json.fields, "[?id == '25'].value | [0]" ) }}
or
{{ $jmespath($json, "fields[?id == '25'].value | [0]" ) }}

See this example workflow

You can test various data structures and filters live at https://jmespath.org/

1 Like