英文:
How to get an key value pair from an object in angular
问题
sample array:
const obj = {
"29": "DTE Queue",
"30": "Services Reporting Sales",
"31": "Services Reporting Ops",
"41": "UPLOAD",
"55": "Support Report"
};
I'm getting input from user as 'ser'. Then output should be { "30": "Services Reporting Sales", "31": "Services Reporting Ops"}. But the output I'm getting is {"30": "Services Reporting Sales"}.
**Method 1:**
getKeyByValue(obj: object, value) {
const matchedEntry = Object.entries(obj).find(entry =>
entry[1].toLowerCase().match(value.toLowerCase()));
return matchedEntry && (<any>Object).fromEntries([matchedEntry])
}
**Method 2:**
getKeyByValue(obj: Object, value) {
try {
return (<any>Object).fromEntries([
Object.entries(obj).find(([key, val]) =>
val.toLowerCase().startsWith(value.toLowerCase())
),
]);
} catch (err) {
console.log("Object not found");
return {};
}
}
英文:
sample array:
const obj = {
"29": "DTE Queue",
"30": "Services Reporting Sales",
"31": "Services Reporting Ops",
"41": "UPLOAD",
"55": "Support Report"
};
I'm getting input from user as 'ser'. Then output should be { "30": "Services Reporting Sales", "31": "Services Reporting Ops"}.But the output I'm getting is {"30": "Services Reporting Sales"}.
Method 1:
getKeyByValue(obj:object, value) {
const matchedEntry = Object.entries(obj).find(entry =>
entry[1].toLowerCase().match(value.toLowerCase()));
return matchedEntry &&(<any>Object).fromEntries([matchedEntry])
}
Method2:
getKeyByValue(obj: Object, value) {
try {
return (<any>Object).fromEntries([
Object.entries(obj).find(([key, val]) =>
val.toLowerCase().startsWith(value.toLowerCase())
),
]);
} catch (err) {
console.log("Object not found");
return {};
}
}
答案1
得分: 1
你正在使用find
。find
返回第一个搜索结果。如果你想要多个结果,可以使用filter
。
const obj = {"29": "DTE Queue", "30": "Services Reporting Sales", "31": "Services Reporting Ops", "41": "UPLOAD", "55": "Support Report"};
function getObjectByValue(object, value) {
return Object.fromEntries(Object.entries(object).filter(([key, val]) => val.toLowerCase().includes(value.toLowerCase())));
}
console.log(getObjectByValue(obj, 'ser'));
console.log(getObjectByValue(obj, 'sup2'));
英文:
You're using find
. find
returns the first search result. If you want multiple results, you can use filter
.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const obj = {"29": "DTE Queue", "30": "Services Reporting Sales", "31": "Services Reporting Ops", "41": "UPLOAD", "55": "Support Report"};
function getObjectByValue(object, value) {
return Object.fromEntries(Object.entries(object).filter(([key, val]) => val.toLowerCase().includes(value.toLowerCase())));
}
console.log(getObjectByValue(obj, 'ser'));
console.log(getObjectByValue(obj, 'sup2'));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论