Necesito una función para filtrar una matriz de objetos según la estructura dada del objeto. Así que tengo este objeto:
{ "2": [ { "fd_id": 16, ...others } ], "3": [ { "fd_id": 2, ...others }, { "fd_id": 3, ...others } ] }Me gustaría filtrar otra matriz basada en este objeto. Como esto;
const result = products.filter(item => { // returns array of numbers [1, 2, 3] const filters = item.filters; if(filters){ // Here must be refactored return ((filters.includes(givenObj[2][0].fd_id)) && (filters.includes(givenObj[3][0].fd_id) || filters.includes(givenObj[3][1].fd_id))); } });Pero esta función debe ser dinámica. Porque el objeto de entrada puede cambiar. Entonces, entre cada padre "&&", y entre cada hijo "||" debe aplicarse la condición. Gracias por cualquier ayuda. Este es el enlace al ejemplo https://jsfiddle.net/cadkt86n/
Una función para hacer un bucle de datos ayudará.
mi logica
fd_id s de los groups usando Array.mapproducts de filtro. Verifique la combinación coincidente en el nodo de filters de la matriz de products . La condición es que debe haber una combinación coincidente en cada nodo de la matriz fdIdList .violín de trabajo
var groups = { "2": [ { "fd_id": 16, "fd_fRef": 2, "fd_ad": "35 - 50", "fd_siraNo": 255, "checked": true } ], "3": [ { "fd_id": 2, "fd_fRef": 3, "fd_ad": "KURU", "fd_siraNo": 255, "checked": true }, { "fd_id": 3, "fd_fRef": 3, "fd_ad": "KARMA", "fd_siraNo": 255, "checked": true } ] } // Aggregates the list of fd_id s - This wil be an array of arrays // [[16],[2,3]] => This will be the value const fdIdList = Object.values(groups).map(a => a.map(b => b.fd_id)); var products = [ { "id": 1, "filters": [2, 3, 4, 13, 16, 17, 18, 19, 31, 48, 309, 318], }, { "id": 2, "filters": [2, 3, 4, 13, 15, 17, 18, 19, 31, 48, 309, 318], } ]; // Check if there is a common element in each node of fdIdList var result = products.filter(item => { const filters = item.filters; if (filters) { let isFound = true; fdIdList.forEach(idListNode => { isFound = isFound && idListNode.filter(value => filters.includes(value)).length > 0; }) return isFound } }); console.log(result)