Ikong
Ikong

Reputation: 2570

Javascript ES2015 check if one of the named key in an object is empty

I have an array that looks like below

process:Array[3]
0:Object
    office_id:""
1:Object
    office_id:6
2:Object
   office_id:""

I want to check if office_id named key is not empty

If I find at least one office_id that is not empty it will return true else if all is empty it will return false.

The default value of office_id is empty string as you can see.

The object is dynamic since I'm using some input select form to add another object with office_id so if they select something another object will be added with office_id equal to that specific select id.

Now, as for validation purpose I need to check if the object process contains an office_id with a numeric value.

Upvotes: 1

Views: 105

Answers (3)

ShibS
ShibS

Reputation: 40

Using simple for loop and more efficient way

function () {
  for(i = 0; i < process.length; i++){
    if (process[i].office_id){
      return true;
      break;
    }
  }

  return false;
}

Using ES5 filter

function () {
  var filteredProcess = process.filter(function(pr) {
    if (pr.office_id){
      return true;
    }
  });

  return filterProcess.length ?
    true: 
    false;
}

Upvotes: 1

djfdev
djfdev

Reputation: 6037

Use Array.prototype.some to verify that at least one member of the array matches your condition:

const result = yourArray.some(item => item !== '')

Upvotes: 0

intentionally-left-nil
intentionally-left-nil

Reputation: 8284

You can use some combined with the javascript truthy-ness to determine if it's empty. Since 0 evaluates to falsey, you need to handle that as a special case. See isEmpty below

const isEmpty = (arr) => arr.some(item => item.office_id === 0 || !!item.office_id);

// This returns false because all the elements are falsey
console.log(isEmpty([
  {
    office_id: "",
  },
  {
    office_id: undefined,
  },
  {
    office_id: null,
  },
  {
    office_id: "",
  },
]));

// This returns true because the number 6
console.log(isEmpty([
  {
    office_id: "",
  },
  {
    office_id: 6,
  },
]));

// This returns true because 0 is special cased
console.log(isEmpty([
  {
    office_id: "",
  },
  {
    office_id: 0,
  },
]));

Upvotes: 0

Related Questions