Tengo una siguiente matriz de mapas
let input = [ {"name":"apple", "type":"fruit", "color": "red"}, {"name":"apple", "type":"fruit", "color": "green"}, {"name":"tomato", "type":"fruit", "color": "red", "taste":"sweet"}, {"name":"tomato", "type":"fruit", "color": "green", "taste":"sour"} ];¿Cómo verifico si hay dos elementos en esta matriz, uno que contiene manzanas rojas y tomates verdes?
Intenté esto:
console.log ( input.some( (subMap) => subMap.name == "tomato" && subMap.color == "green") && input.some( (subMap) => subMap.name == "apple" && subMap.color == "red")); Para la matriz anterior, esto devuelve true .
Buscando una forma más concisa de verificar esto.
Algo como
input =[ {"name":"apple", "type":"fruit", "color": "red"}, {"name":"apple", "type":"fruit", "color": "green"}, {"name":"tomato", "type":"fruit", "color": "red", "taste":"sweet"}, {"name":"tomato", "type":"fruit", "color": "green", "taste":"sour"} ]; subArray = [{"name" : "apple", "color":"red"} , {"name":"tomato", "color" : "green"}] //This function should return true (input.hasElementsMatching(subArray)) => trueGracias por adelantado
Entonces, para cada objeto en el subArray , necesita encontrar un elemento en la input que contenga todas las claves/valores de ese objeto
function arrayContainsObjects(array, check) { return check.every((objectToCheck) => { return array.some((item) => { return Object.entries(objectToCheck).every( ([key, value]) => item[key] === value ); }); }); } const input = [{ "name": "apple", "type": "fruit", "color": "red" }, { "name": "apple", "type": "fruit", "color": "green" }, { "name": "tomato", "type": "fruit", "color": "red", "taste": "sweet" }, { "name": "tomato", "type": "fruit", "color": "green", "taste": "sour" } ]; const subArray = [{ "name": "apple", "color": "red" }, { "name": "tomato", "color": "green" }]; console.log( arrayContainsObjects(input,subArray) );