Search code examples
javascriptarraysobject

How to get an Key value pair from a array of objects in angular


Sample array of objects:

{"29": "DTE Queue", "30": "Services Reporting Sales", "31": "Services Reporting Ops", "41": "UPLOAD", "55": "Support Report"}.

I'm getting input from user as 'sup'. Then output should be {"55": "Support Report"}.

function getKeyByValue(object, value) {
  return Object.keys(object).find((key) => object[key] === value);
}

Solution

  • You can convert the object to an array of entries, find the entry and convert it back to an object:

    const obj = {"29": "DTE Queue", "30": "Services Reporting Sales", "31": "Services Reporting Ops", "41": "UPLOAD", "55": "Support Report"};
    
    function getObjectByValue(object, value) {
      try {
        return Object.fromEntries([Object.entries(object).find(([key, val]) => val.toLowerCase().includes(value.toLowerCase()))]);
      } catch (err) {
        console.error('Object not found');
        return {};
      }
    }
    
    console.log(getObjectByValue(obj, 'sup'));
    console.log(getObjectByValue(obj, 'sup2'));