Trying to retrieve the internal array (tags) from the following structure:
"tags" array contains the tag with "function" values, to get this I use the following expression:
let func = parsed.filter(x => x.tags.filter(x => x.tag == "function"));
being parsed the structure, but the result is:
It is including an array that doesn't contain "function" value in the "tag" property. How can I get only the arrays that contain "function" values in the "tag" property?
CodePudding user response:
Your problem is that the inner filter x.tags.filter(x => x.tag == "function")
returns empty array []
which is truthy value even when it does not find any tag function
.
You need to make sure tu return true/false or at least correct truthy/falsy value.
Simple fix, just add .length
:
let func = parsed.filter(x => x.tags.filter(x => x.tag == "function").length);
Zero 0
is falsy value and anything greater than 0
like 1
etc.
is truthy
Test:
var arr = [
{ tags: [{ tag: 'function' }]},
{ tags: [{ tag: 'function2' }]}
].filter(x => x.tags.filter(x => x.tag == "function").length);
// arr is [{ tags: [{ tag: 'function' }]}]
console.log(arr);