Elimine datos de mi matriz anidada de objetos haciendo coincidir valores. En mi caso, quiero eliminar los objetos que NO están activos. Por lo tanto, todos los objetos que contengan un 0 activo deben eliminarse.
[ { "id" : 1, "title" : 'list of...', "goals": [ { "id": 1569, "active": 0 }, { "id": 1570, "active": 1 }, { "id": 1571, "active": 0 } ], }, { "id" : 2, "title" : 'more goals', "goals": [ { "id": 1069, "active": 0 }, { "id": 1070, "active": 1 }, ], }, ]Lo siguiente devolverá la matriz en un estado sin cambios
public stripGoalsByInactiveGoals(clusters) { return clusters.filter(cluster => cluster.goals.filter(goal => goal.active === 1) ); }array.filter espera un booleano para saber si tiene que filtrar datos o no
en su caso, tiene una matriz de matrices, desea filtrar la matriz "sub" por objetivo activo
si desea mantener solo los objetivos activos, cambie su primer filtro por mapa para devolver un valor de modificación de su matriz filtrado por una condición
function stripGoalsByInactiveGoals(clusters) { return clusters.map(cluster => { return { goals: cluster.goals.filter(goal => goal.active) }; }); } var data = [{ "goals": [{ "id": 1569, "active": 0 }, { "id": 1570, "active": 1 }, { "id": 1571, "active": 0 } ], }, { "goals": [{ "id": 1069, "active": 0 }, { "id": 1070, "active": 1 }, ], }, ]; function stripGoalsByInactiveGoals(clusters) { return clusters.map(cluster => { return { goals: cluster.goals.filter(goal => goal.active) }; }); } console.log(stripGoalsByInactiveGoals(data));Puede crear otra matriz (para el caso en que también necesite la entrada sin cambios) y repetir la entrada, agregando la matriz de objetivos filtrados de cada objeto miembro. También podría evitar agregar el elemento si los objetivos están vacíos después del filtro, pero este ejemplo no hace esto porque no se especificó como un requisito.
let input = [ { "goals": [ { "id": 1569, "active": 0 }, { "id": 1570, "active": 1 }, { "id": 1571, "active": 0 } ], }, { "goals": [ { "id": 1069, "active": 0 }, { "id": 1070, "active": 1 }, ], }, ] let output = []; for (let item of input) { output.push({goals: item.goals.filter(element => (element.active))}) } console.log(output);Puede seguir esto para un enfoque dinámico:
stripGoalsByInactiveGoals(clusters) { var res = []; this.data.forEach((item) => { let itemObj = {}; Object.keys(item).forEach((key) => { itemObj[key] = item[key].filter(x => x.active != 0); res.push(itemObj); }); }); return res; }