【发布时间】:2020-08-28 04:02:33
【问题描述】:
我需要在具有多个对象的数组中深入过滤数组内的类别对象。在 API 调用中,我将拥有这个具有嵌套类别的对象数组。如果每个对象包含特定的类别 ID,我需要过滤它。这是 JSON -
items_loop: [
{
ID: 1,
name: "Item A",
taxonomy: {
categories: [
{
name: "Book",
parent: 12,
taxonomy: "category",
},
{
name: "Cover",
parent: 4,
taxonomy: "category",
},
{
name: "Other",
parent: 15,
taxonomy: "category",
},
],
},
},
{
ID: 2,
name: "Item B",
taxonomy: {
categories: [
{
name: "Toys",
parent: 16,
taxonomy: "category",
},
{
name: "Book",
parent: 12,
taxonomy: "category",
},
{
name: "Other",
parent: 15,
taxonomy: "category",
},
],
},
},
{
ID: 3,
name: "Item C",
taxonomy: {
categories: [
{
name: "Ext",
parent: 6,
taxonomy: "category",
},
{
name: "Cover",
parent: 4,
taxonomy: "category",
},
{
name: "Other",
parent: 15,
taxonomy: "category",
},
],
},
},
]
我想用只包含 "parent" : 15 的对象创建一个新数组,但是如何深入过滤这 3 个对象?我试过了,但它不起作用
function findInObjArray(array, value) {
var found = []
// Helper to search obj for value
function findInObj(obj, value) {
return Object.values(obj).some((v) =>
// If v is an object, call recursively
typeof v == "object" && v != "null"
? findInObj(v, value)
: // If string, check if value is part of v
typeof v == "string"
? v.indexOf(value) >= 0
: // Check numbers, make NaN == NaN
typeof v == "number"
? v === value || (isNaN(v) && isNaN(value))
: // Otherwise look for strict equality: null, undefined, function, boolean
v === value
)
}
array.forEach(function (obj) {
if (findInObj(obj, value)) found.push(obj)
})
return found
}
【问题讨论】:
-
condition ? val1 : val2 : val3语法无效。
标签: javascript