Home > Enterprise >  Filter Object passed on Value Properties
Filter Object passed on Value Properties

Time:12-16

I have an object like this:

let obj = {'machine1':{'err':'404', switch:false},
           'gadget1':{'err':'404', switch:true}}

Would not pass validation. => return false



let obj2 = {'machine2':{'err':'404', switch:false},
           'gadget2':{'err':null, switch:true}}

Would pass validation. => return true

I want to return true when every key in the object in which the switch is set to true does not have any errors (see obj2). (For machine2 the '404' error does not matter, because the switch is set to false.)

I tried something like that, but didn't get far.

function try() { 
  for (x in obj) {
    obj[x].filter(x=>y.switch === true)
}
}

Thanks for reading!

CodePudding user response:

you could do something like the follow:

const test = obj => Object.keys(obj).every(k => !obj[k].switch || obj[k].err === null)

So you check if every key in the object has switch set to false or the err equal to null.

CodePudding user response:

You can do it by usign entries and every helpers of Array, like this:

let obj = {
  'machine1': {
    'err': '404',
    switch: false
  },
  'gadget1': {
    'err': '404',
    switch: true
  }
}

let obj2 = {
  'machine2': {
    'err': '404',
    switch: false
  },
  'gadget2': {
    'err': null,
    switch: true
  }
};
const validate = (data) => {
  return Object.entries(data).every(([key, value]) => !value.switch || value.err === null)
}

console.log(validate(obj));
console.log(validate(obj2));

  • Related