我有一个过滤函数,只有在传入JSON时才返回undefined。我想使用这个函数来过滤对象,JSON或其他任何东西。什么是在对象和JSON上使这个工作的最佳方法?
let a = [{
"employees": {
"employee": [{
"id": "1",
"firstName": "Tom",
"lastName": "Cruise"
}, {
"id": "2",
"firstName": "Maria",
"lastName": "Sharapova"
}, {
"id": "3",
"firstName": "James",
"lastName": "Bond"
}]
}
}];
var b = [{
name: '',
grade: 'x'
}, {
name: 'yaya',
grade: 'x'
}, {
name: 'x',
frade: 'd'
}, {
name: 'a',
grade: 'b'
}];
function findIt(arr, searchKey) {
return arr.filter(obj => Object.keys(obj).some(key => obj[key].includes(searchKey)));
}
if (a) {
console.log("I found: ", findIt(a, "James")); // breaks
}
if (b) {
console.log("I found: ", findIt(b, "yaya")); // works fine
}
答案 0 :(得分:2)
您需要引用内部数组进行搜索。
findIt(a[0].employees.employee, "James"));
// ^^^^^^^^^^^^^^^^^^^^^^
let a = [{ employees: { employee: [{ id: "1", firstName: "Tom", lastName: "Cruise" }, { id: "2", firstName: "Maria", lastName: "Sharapova" }, { id: "3", firstName: "James", lastName: "Bond" }] } }];
var b = [{ name: '', grade: 'x' }, { name: 'yaya', grade: 'x' }, { name: 'x', frade: 'd' }, { name: 'a', grade: 'b' }];
function findIt(arr, searchKey) {
return arr.filter(obj => Object.keys(obj).some(key => obj[key].includes(searchKey)));
}
console.log(findIt(a[0].employees.employee, "James"));
console.log(findIt(b, "yaya"));
为了更深入的发现,您可以使用递归方法。
function findIt(object, search) {
function find(k) {
if (object[k] === search) {
return result = object;
}
return result = findIt(object[k], search);
}
var result;
if (object && typeof object === 'object') {
Object.keys(object).some(find);
}
return result;
}
var a = [{ employees: { employee: [{ id: "1", firstName: "Tom", lastName: "Cruise" }, { id: "2", firstName: "Maria", lastName: "Sharapova" }, { id: "3", firstName: "James", lastName: "Bond" }] } }],
b = [{ name: '', grade: 'x' }, { name: 'yaya', grade: 'x' }, { name: 'x', frade: 'd' }, { name: 'a', grade: 'b' }];
console.log(findIt(a, "James"));
console.log(findIt(b, "yaya"));
console.log(findIt(a, "foo")); // undefined
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
您可以尝试进行字符串搜索。
JSON.stringify
:<something>SearchValue
。
let a = [{ employees: { employee: [{ id: "1", firstName: "Tom", lastName: "Cruise" }, { id: "2", firstName: "Maria", lastName: "Sharapova" }, { id: "3", firstName: "James", lastName: "Bond" }] } }];
var b = [{ name: '', grade: 'x' }, { name: 'yaya', grade: 'x' }, { name: 'x', frade: 'd' }, { name: 'a', grade: 'b' }];
function findIt(arr, searchKey) {
let reg = new RegExp(':(.*?)' + searchKey, 'g');
return arr.filter(obj => reg.test(JSON.stringify(obj)));
}
console.log("I found: ", findIt(a, "James")); // breaks
console.log("I found: ", findIt(a[0].employees.employee, "James")); // breaks
console.log("I found: ", findIt(b, "yaya")); // works fine