Given an array of objects like this:
let kandidaten = [{
name: "Pfennig",
branche: "Banken",
thema: "Parkplätze"
},
{
name: "Heller",
branche: "Banken",
thema: "Gebühren"
},
{
name: "Wolf",
branche: "Beratung",
thema: "Ausbildung"
},
{
name: "Schaf",
branche: "Hotel",
thema: "Ausbildung"
}
]
I want to check this array of objects via an user-input which asks for two condition: “branche” and “thema”. If the object matches both conditions it should be displayed. How should I do this?
This is the code, to get the input from the HTML:
const selectedBranche = document.getElementById("branche").value;
const selectedThema = document.getElementById("thema").value;
function getSelectValue() {
document.getElementById("outBranche").innerHTML = selectedBranche;
document.getElementById("outThema").innerHTML = selectedThema;
}
For checking the object-array I did this:
function branchenCheck(selectedBranche, selectedThema) {
for (var i = 0; i < kandidaten.length; i++) {
for (key in kandidaten[i]) {
if (kandidaten[i][key].indexOf(selectedBranche) != -1) {
resultBranche.push(kandidaten[i]);
}
}
}
console.log(resultBranche)
It works, I get all objects which match the query “Branche”.
But I don’t know, how the code should look, if two queries should be matched. “&&” does not work. Like in;
function branchenCheck(selectedBranche, selectedThema) {
for (var i = 0; i < kandidaten.length; i++) {
for (key in kandidaten[i]) {
if (kandidaten[i][key].indexOf(selectedBranche) && kandidaten[i][key].indexOf(selectedThema) != -1) {
resultBranche.push(kandidaten[i]);
}
}
}
Maybe it is possible to create a filter object. Like
let filter = {
branche: selectedBranche,
thema: selectedThema
}
But I does not work too. Maybe because “selectedBranche” and “selectedThema” are variables?
Thank you in advance!