Home > Software engineering >  How to optimise if condition to check for particular array of json object in javaScript
How to optimise if condition to check for particular array of json object in javaScript

Time:04-29

I want code optimisation for if condition because I've to add more key value pair in if condition with &&. So I've array of object as follow just as example.

let arr = [{
    a:12,
    b:14,
    c:undefined,
    d:undefined,
    e:56,
    f:"file 1",
    g:"file 2",
    h:undefined
}]
for(let key of arr){
if(key.a!==undefined && key.b!==undefined && key.c!==undefined && key.d!==undefined && key.e!==undefined && key.f!==undefined && key.g!==undefined){
console.log("code works")
}else{
console.log("fails")}
}

So I've to add multiple key value to check for condition for undefined value. I'm trying to optimise please help or any suggestion. thanks you.

CodePudding user response:

You can use Object.values() and some() to write a shorter code. This is not a huge optimization

let arr = [{
    a:12,
    b:14,
    c:undefined,
    d:undefined,
    e:56,
    f:"file 1",
    g:"file 2",
    h:undefined
}]
for(let key of arr){
if(Object.values(key).some((x) => x===undefined)){
console.log("fails")
}else{
console.log("code works")
}
}

CodePudding user response:

Create a function that accepts an object as an argument, gets its values, and then use some to check if any of the values are undefined. some returns after finding the first match to the condition.

const arr=[{a:12,b:14,c:undefined,d:undefined,e:56,f:'file 1',g:'file 2',h:undefined},{a:12,b:14,c:3,d:'bob from accounting',e:56,f:'file 1',g:'file 2',h:23},{a:12,b:14,c:3,d:'bob from accounting',e:56,f:'file 1',g:'file 2',h:undefined}];

function test(obj) {
  const values = Object.values(obj);
  return values.some(p => p === undefined);
}

const out = arr.map((obj, i) => {
  return `Code ${test(arr[i]) ? 'fails' : 'works'}`;
});

console.log(out);

CodePudding user response:

If I understand the requirement correctly, You have dynamic properties in an object and you want to check if all the properties in an object having values. If Yes,

Try this :

let arr = [{
    a:12,
    b:14,
    c:undefined,
    d:undefined,
    e:56,
    f:"file 1",
    g:"file 2",
    h:undefined
}];

arr.forEach(obj => {
  let str = '';
    Object.keys(obj).forEach(key => {
    str = obj[key] ? 'code works' : 'fails'
  })
  console.log(str);
});

  • Related