我有一个看起来像这样的对象:
var myObj = {
"account id": "123TRANS",
"account name": "Optimus Prime",
"creator id": "Prime",
"contact tel": 08915243209,
"house no": 209,
"is registered": true,
"price": 398.83,
"first name": "paul",
"last name": "jones",
"dob": "27-Jun-1978 00:00:00",
"previous orders": true,
"average price": 123.78,
"lace colour": "blue",
"first line": "Jupiter Close",
"city": "New York",
"alias": "Jupiter",
"role": "Accountant"
}
在我的 HTML 页面上,我有一个 <input>
用户可以在其中输入文本的字段(至少需要 3 个字符)。我能够根据输入字符串的匹配项过滤上面的整个对象。
例如,如果 string = "Prime"响应为:
{
"account name": "Optimus Prime",
"creator id": "Prime",
}
例如,string = "acc"响应为:
{
"account id": "123TRANS",
"account name": "Optimus Prime",
"role": "Accountant"
}
例如,string = "209"响应为:
{
"contact tel": 08915243209,
"house no": 209,
}
我尝试过使用.reduce
,但是这会产生不同的结果:
var myObject = {from above};
var filter = 'prime';
myObject = Object.keys(myObject).reduce((r, e) => {
// Avoid int/float/bool and check key + value
if(e !== 'contact tel' &&
e !== 'house no' &&
e !== 'previous orders') {
// Check Key or Value for filter
if(myObject[e].toLowerCase().includes(filter.toLowerCase) || e.toLowerCase().includes(filter.toLowerCase())) {
r[e] = myObject[e]
}
}
// Check int/float/bool and check key
if(e === 'contact tel' ||
e === 'house no' ||
e === 'previous orders') {
// Check Key or Value for filter
if(e.toLowerCase().includes(filter.toLowerCase())) {
r[e] = myObject[e]
}
}
return r;
}, {})
我也可以访问 lodash,但是找不到任何检查键和值的内容,只有键或值。
最佳答案
您可以获取条目,过滤键和值并构建一个新对象作为结果。
function find(object, search) {
search = search.toLowerCase();
return Object.assign(...Object
.entries(object)
.filter(a => a.some(s => s.toString().toLowerCase().includes(search)))
.map(([k, v]) => ({ [k]: v }))
);
}
var myObj = { "account id": "123TRANS", "account name": "Optimus Prime", "creator id": "Prime", "contact tel": "08915243209", "house no": 209, "is registered": true, price: 398.83, "first name": "paul", "last name": "jones", dob: "27-Jun-1978 00:00:00", "previous orders": true, "average price": 123.78, "lace colour": "blue", "first line": "Jupiter Close", city: "New York", alias: "Jupiter", role: "Accountant" };
console.log(find(myObj, 'ACC'));
关于javascript - 过滤对象键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54665273/