Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement conditions specified in an array

I have the following array:

array = ["ProgA", "ProgC", "ProgG"]

This array can change depending on the user input.

I have the following Json File:

    {"ABC":{

        "ProgA": 1, 
        "ProgB": 0, 
        "ProgC": 1,  
        "ProgD": 0, 
        "ProgE": 0, 
        "ProgF": 1, 
        "ProgG": 1, 
        "ProgH": 0 


    },
    "DEF":{

        "ProgA": 1, 
        "ProgB": 0, 
        "ProgC": 0,  
        "ProgD": 0, 
        "ProgE": 1, 
        "ProgF": 0, 
        "ProgG": 1, 
        "ProgH": 0 


    },
    "GHI":{

        "ProgA": 1, 
        "ProgB": 1, 
        "ProgC": 1,  
        "ProgD": 1, 
        "ProgE": 1, 
        "ProgF": 1, 
        "ProgG": 1, 
        "ProgH": 1


    },
    "JKL":{

        "ProgA": 1, 
        "ProgB": 0, 
        "ProgC": 1,  
        "ProgD": 1, 
        "ProgE": 0, 
        "ProgF": 1, 
        "ProgG": 0, 
        "ProgH": 1 


    },
    "MNO":{

        "ProgA": 1, 
        "ProgB": 1, 
        "ProgC": 1,  
        "ProgD": 0, 
        "ProgE": 1, 
        "ProgF": 1, 
        "ProgG": 1, 
        "ProgH": 1

    }}

My goal is to basically return all the names ("ABC", "DEF" etc) which have the ProgA, ProgC and ProgG == 1

I am not sure how to evaluate the if statements when the conditions are in an array which can change.

like image 621
Morpheus Avatar asked Dec 14 '22 05:12

Morpheus


1 Answers

You can do this with filter() and every()

var array = ["ProgA", "ProgC", "ProgG"];
var obj = {"ABC":{"ProgA":1,"ProgB":0,"ProgC":1,"ProgD":0,"ProgE":0,"ProgF":1,"ProgG":1,"ProgH":0},"DEF":{"ProgA":1,"ProgB":0,"ProgC":0,"ProgD":0,"ProgE":1,"ProgF":0,"ProgG":1,"ProgH":0},"GHI":{"ProgA":1,"ProgB":1,"ProgC":1,"ProgD":1,"ProgE":1,"ProgF":1,"ProgG":1,"ProgH":1},"JKL":{"ProgA":1,"ProgB":0,"ProgC":1,"ProgD":1,"ProgE":0,"ProgF":1,"ProgG":0,"ProgH":1},"MNO":{"ProgA":1,"ProgB":1,"ProgC":1,"ProgD":0,"ProgE":1,"ProgF":1,"ProgG":1,"ProgH":1}}

var result = Object.keys(obj).filter(function(e) {
  return array.every(function(a) {
    return obj[e][a] == 1;
  });
});

console.log(result)
like image 158
Nenad Vracar Avatar answered Jan 04 '23 13:01

Nenad Vracar