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);
}
CodePudding user response:
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'));
CodePudding user response:
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'));
CodePudding user response:
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])
}