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);
}
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'));
You can use Object.entries()
and Object.fromEntries()
for the result you are expecting:
const obj = { "29": "DTE Queue", "30": "Services Reporting Sales", "31": "Services Reporting Ops", "41": "UPLOAD", "55": "Support Report" }; function getKeyByValue(object, value) { const res = Object.entries(object).find((arr) => arr.includes(value)); if (res) { return Object.fromEntries([res]); } } console.log(getKeyByValue(obj, 'Support Report'));
const obj = { "29": "DTE Queue", "30": "Services Reporting Sales", "31": "Services Reporting Ops", "41": "UPLOAD", "55": "Support Report" }; console.log(getKeyByValue(obj, 'sup')) function getKeyByValue(obj, value) { const matchedEntry = Object.entries(obj).find(entry => entry[1].toLowerCase().match(value.toLowerCase())); return matchedEntry && Object.fromEntries([matchedEntry]) }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.