gpt4 book ai didi

javascript - 过滤对象键和值

转载 作者:行者123 更新时间:2023-11-30 11:08:39 25 4
gpt4 key购买 nike

我有一个看起来像这样的对象:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com