我有一个带有嵌套对象的数组。像这样:
const results = [
{
general: {
orderID: '5567',
created: 1548765626101,
status: 'new'
},
company: {
companyName: 'company x',
companyEmail: 'info@companyx.com',
companyContact: 'John Doe'
},
customer: {
customerName: 'Jane Doe',
customerEmail: 'janedoe@email.com'
},
products: [
{
productID: 4765756,
productName: 'Product x',
productDescription: 'Description for product x'
},
{
productID: 4767839,
productName: 'Product y',
productDescription: 'Description for product y'
}
],
payment: {
price: 1000,
method: 'cash'
}
},
]
(为使结构保持一点点,我只为这个问题插入了一个结果对象。但是,我们说结果数组中有100个元素。)
用户可以输入搜索词并选中/取消选中包含或不包含这些键的键。键被硬编码在列表中。
例如。用户输入“ jane”,然后将customerName和customerEmail作为要搜索的键。或者用户输入“ x”并检查productName。
如何动态搜索这些选中的键?我已经在数组中具有选定的键。
因此,对于第一个示例,我有['customerName', 'customerEmail']
。
第二个是['productName']
我以前使用过array.filter()
来处理硬编码键,但是我不知道如何过滤这些动态键。
有人可以帮我分解不同的步骤吗?我正在使用es6,没有外部库。
答案 0 :(得分:1)
您需要遍历results
数组,然后在每个对象中深度搜索匹配项。为此,您将需要
类似的东西
const deepSearcher = (fields, query) =>
function matcher(object) {
const keys = Object.keys(object);
return keys.some(key => {
const value = object[key];
// handle sub arrays
if (Array.isArray(value)) return value.some(matcher);
// handle sub objects
if (value instanceof Object) return matcher(value);
// handle testable values
if (fields.includes(key)) {
// handle strings
if (typeof value === "string") return value.includes(query);
// handle numbers
return value.toString() === query.toString();
}
return false;
});
};
此函数创建一个与.filter
方法一起使用的匹配器。
const customerFilter = deepSearcher(['customerName', 'customerEmail'], 'jane')
const found = results.filter(customerFilter);
或者您可以将其直接传递给.filter
const found = results.filter(deepSearcher(['customerName', 'customerEmail'], 'jane'));
您传递给deepSearcher的字段不必属于同一对象。匹配器将测试任何东西是否匹配(,但它们必须指向字符串/数字,此代码才能起作用。)
有效的测试用例
const results = [{
general: {
orderID: "5567",
created: 1548765626101,
status: "new"
},
company: {
companyName: "company x",
companyEmail: "info@companyx.com",
companyContact: "John Doe"
},
customer: {
customerName: "Jane Doe",
customerEmail: "janedoe@email.com"
},
products: [{
productID: 4765756,
productName: "Product x",
productDescription: "Description for product x"
},
{
productID: 4767839,
productName: "Product y",
productDescription: "Description for product y"
}
],
payment: {
price: 1000,
method: "cash"
}
}];
const deepSearcher = (fields, query) =>
function matcher(object) {
const keys = Object.keys(object);
return keys.some(key => {
const value = object[key];
// handle sub arrays
if (Array.isArray(value)) return value.some(matcher);
// handle sub objects
if (value instanceof Object) return matcher(value);
// handle testable values
if (fields.includes(key)) {
// handle strings
if (typeof value === "string") return value.includes(query);
// handle numbers
return value.toString() === query.toString();
}
return false;
});
};
const matchingCustomer = results.filter(deepSearcher(["customerName", "customerEmail"], 'jane'));
console.log('results with matching customer:', matchingCustomer.length);
const matchingProduct = results.filter(deepSearcher(["productName"], 'x'));
console.log('results with matching product:', matchingProduct.length);
const matchingPrice = results.filter(deepSearcher(["price"], '1000'));
console.log('results with matching price:', matchingPrice.length);
const nonMatchingPrice = results.filter(deepSearcher(["price"], '500'));
console.log('results with non matching price:', nonMatchingPrice.length);
答案 1 :(得分:0)
也许是这样?请记住,“ searchTerm”是类型敏感的。
用法:搜索(结果,['companyName','productName'],'x');
/**
* Returns an array of objects which contains at least one 'searchKey' whose value
* matches THE 'searchTerm'.
*/
function search( inp, searchKeys, searchTerm ) {
let retArray = [];
function rdp( inp, searchKeys, searchTerm ) {
if ( Array.isArray(inp) ) {
if (inp.length > 0) {
inp.forEach(elem => {
rdp( elem, searchKeys, searchTerm );
});
}
}
else {
Object.keys( inp ).forEach( prop => {
if ( Array.isArray( inp[ prop ] ) || ( typeof inp[ prop ] == 'object')) {
rdp( inp[ prop ], searchKeys, searchTerm );
}
else {
searchKeys.forEach( key => {
if (( prop == key ) && // key match
( prop in inp)) { // search term found
switch ( typeof inp[prop] ) {
case 'string' : if (inp[ prop ].indexOf( searchTerm ) > -1) { retArray.push( inp ); } break;
case 'number' : if ( inp[ prop ] === searchTerm ) { retArray.push( inp ); } break;
}
}
});
}
});
}
}
rdp( inp, searchKeys, searchTerm );
return retArray;
}