javascript - JS 搜索对象键和值
问题描述
我有一个大型 JS 对象(大约 7000 个条目),看起来像,
var jsobject = {
"/football/": {
"title": "(:title)",
"description": "Shop (:title) online ",
"index": "true",
"follow": "true",
"CANONICAL": "/football/"
},
"/league/": {
"title": "(:title)",
"description": "Shop (:title) online",
"index": "true",
"follow": "true",
"CANONICAL": "/bayern-munich/p/replica"
},
"/club/fulham/": {
"title": "(:title)",
"description": "Shop (:title) online for football league",
"index": "true",
"follow": "true",
"CANONICAL": "/fulham/"
},
"/championship/": {
"title": "(:title)",
"description": "Shop (:title) online for championship",
"index": "true",
"follow": "true",
"CANONICAL": "/socks/"
}
};
现在我想在对象中搜索搜索键(比如“足球”)退出对象“键”或“值”。
我已经使用下面的代码来实现这一点,但它需要的时间比预期的要多。这个 javascript 代码是用 Angular JS 和 Javascript 编写的。你能建议我一个更快的方法吗?
angular.forEach(
Object.keys(jsobject), function (data) {
let obj = String(angular.lowercase(JSON.stringify(jsobject[data])));
if (obj.includes(searchKey) || String(angular.lowercase(data)).includes(searchKey)) {
searchResults[data] = jsobject[data];
}
},
searchResults.jsondata
);
如果我用“足球”搜索,我希望输出如下所示,
{
"/football/": {
"title": "(:title)",
"description": "Shop (:title) online ",
"index": "true",
"follow": "true",
"CANONICAL": "/football/"
},
"/club/fulham/": {
"title": "(:title)",
"description": "Shop (:title) online for football league",
"index": "true",
"follow": "true",
"CANONICAL": "/fulham/"
}
};
解决方案
您可以混合使用Object.entries
, Array.filter
&Array.some
来实现您的目标。
下面是一个例子。
var jsobject = {
"/football/": {
"title": "(:title)",
"description": "Shop (:title) online ",
"index": "true",
"follow": "true",
"CANONICAL": "/football/"
},
"/league/": {
"title": "(:title)",
"description": "Shop (:title) online",
"index": "true",
"follow": "true",
"CANONICAL": "/bayern-munich/p/replica"
},
"/club/fulham/": {
"title": "(:title)",
"description": "Shop (:title) online for football league",
"index": "true",
"follow": "true",
"CANONICAL": "/fulham/"
},
"/championship/": {
"title": "(:title)",
"description": "Shop (:title) online for championship",
"index": "true",
"follow": "true",
"CANONICAL": "/socks/"
}
};
function filterAll(obj, search) {
return Object.fromEntries(
Object.entries(obj).filter(([k,v]) =>
k.toLowerCase().includes(search)
|| Object.entries(v).some(([k,v]) =>
typeof v === 'string'
&& v.toLowerCase().includes(search)
)));
}
console.log(filterAll(jsobject, 'football'));
推荐阅读
- angular - 如何将布尔值从 http 请求发送到组件?(Angular)
- matlab - MATLAB 的隐式广播是否根据周围代码进行优化?
- azure - vpn 和 mproto 代理将他们的访问权限分配给 azure 私有 ip 而不是公共 ip
- envoyproxy - lua 之前的 Envoy ext_authz 过滤器
- django-rest-framework - 如何使用 django rest api 为注册用户发送电子邮件确认
- c - STM32H7 SPI Nor Flash 设备总是忙 IS25LP128F
- azure - 未指定源参数 cake
- r - R中多项式MLE的简单数值估计问题
- python - 如何在 tkinter 的顶级小部件中导入我的图表
- azure - New-AzKeyVault - 提供的信息未映射到 AD 对象 ID