Mi matriz de objetos anidados se ve así junto con la matriz para que coincida con
let findThis = ["Water"]; let arrayOfElements = [ { "code": "a", "templates": [ { "templateCode": "Water", "title": "Earth" }, { "templateCode": "Milk", "title": "Sky" } ] }, { "code": "b", "templates": [] }, { "code": "c", "templates": [ { "templateCode": "Water", "title": "Earth" }, { "templateCode": "Tree", "title": "Moon" } }, { "code": "d", "templates": [ { "templateCode": "Tooth", "title": "Tiger" } } ] Quiero extraer aquellos objetos cuyo templateCode sea Water . Así que mi última matriz devuelta debería verse así.
let result = [ { "code": "a", "templates": [ { "templateCode": "Water", "title": "Earth" }, { "templateCode": "Milk", "title": "Sky" } ] }, { "code": "c", "templates": [ { "templateCode": "Water", "title": "Earth" }, { "templateCode": "Tree", "title": "Moon" } } ]Lo intenté:
arrayOfElements.filter(x => x.templates.filter(y => findThis.includes(y.templateCode)));Pero está devolviendo la matriz completa y no funciona.
Debe filter arrayOfElements con la condición de cualquier templateCode existente dentro de findThis array.
let findThis = ["Water"]; let arrayOfElements = [ { "code": "a", "templates": [ { "templateCode": "Water", "title": "Earth" }, { "templateCode": "Milk", "title": "Sky" } ] }, { "code": "b", "templates": [] }, { "code": "c", "templates": [ { "templateCode": "Water", "title": "Earth" }, { "templateCode": "Tree", "title": "Moon" } ] }, { "code": "d", "templates": [ { "templateCode": "Tooth", "title": "Tiger" } ] } ] const result = arrayOfElements.filter(item => item.templates.some(t => findThis.includes(t.templateCode))) console.log(result)