Load an object from another object by value of a certain key
getObjectFromDataByKeyValue.js
/**
* Loads an object from another object by value of a certain key.
*
* @usage
* data = [
* 'foo': {
* 'id' => 5,
* 'label' => 'Foo'
* },
* 'bar': {
* 'id' => 6,
* 'label' => 'Bar'
* }
* ]
* foo = getObjectFromDataByKeyValue('id', 5, data)
*
* @param key
* The key we are comparing our value with.
* @param value
* The value the key should have.
* @param data
* The data you want to search in.
* @returns {unknown}
*/
function getObjectFromDataByKeyValue(key, value, data) {
return Object.values(data).find(o => o[key] === value)
}
Issue:
You need to load an object by a value in a nested data structure, e.g. by its ID.