I need to filter in deep the categories object inside an array, in an array with multiple objects. In an API call , I will have this array of objects with nested categories. I need to filter each object if it contains specific category id. This is the 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",
},
],
},
},
]
I want to make a new array with object that contains only "parent" : 15, but how I can filter in deep this 3 object ? I tried with this, but it's not working
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 : val3is invalid syntax.