let products = [
{
name: "A",
color: "Blue",
size: {
size1: 1,
size2: 2,
size3: 3,
},
},
{
name: "B",
color: "Blue",
size: {
size1: 5,
size2: 19,
size3: 22,
},
},
{ name: "C", color: "Black", size: 70 },
{ name: "D", color: "Green", size: 50 },
];
filters = ['Blue','2'];
结果必须是检查数组中所有字符串的对象
{
name: "A",
color: "Blue",
size: {
size1: 1,
size2: 2,
size3: 3,
},
},
无论其值(value)如何,研究都必须被接受
最佳答案
您可以通过以某种方式使用堆栈来解析嵌套,无论是通过递归还是显式迭代地使用堆栈。这是一个递归解决方案:
function getFiltered(obj, filters, found = null) {
let outermostCall = (found === null);
if (outermostCall) { //outermost call
found = [];
for (let index = 0; index < filters.length; index++) {
found[index] = false;
}
}
for (let key in obj) {
if (typeof obj[key] === 'object') {
let tempFound = getFiltered(obj[key], filters, found);
for (let index = 0; index < found.length; index++) {
if (tempFound[index]) found[index] = true;
}
} else {
let foundIndex = -1;
for (let index = 0; index < filters.length; index++) {
if (filters[index] == obj[key]) {
foundIndex = index;
index = filters.length;
}
}
if (foundIndex >= 0) {
found[foundIndex] = true;
}
}
}
if (outermostCall) {
return !found.filter(item => !item).length;
}
return found;
}
function getAllFiltered(array, filters) {
let output = [];
for (let obj of array) {
if (getFiltered(obj, filters)) output.push(obj);
}
return output;
}
let products = [
{
name: "A",
color: "Blue",
size: {
size1: 1,
size2: 2,
size3: 3,
},
},
{
name: "B",
color: "Blue",
size: {
size1: 5,
size2: 19,
size3: 22,
},
},
{ name: "C", color: "Black", size: 70 },
{ name: "D", color: "Green", size: 50 },
];
let filters = ['Blue','2'];
console.log(getAllFiltered(products, filters));
关于javascript - 如何使用字符串数组过滤嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74489636/