0

I have a js array of objects as follows:

var person = [{
  firstName: "",
  lastName: "Doe",
  age: 46
}, {
  firstName: "John",
  lastName: "",
  age: 35
}];  

How do i find out if at least of the objects in the array, for eg firstName: or lastName: is empty or not? The result of the called function needs only to be true or false.

1
  • npm install joi if it is in node. for browsers there are also plenty of validators of all kinds Commented Dec 31, 2017 at 5:44

3 Answers 3

1

You can use filter & length like:

const isEmpty = person.filter(x => !x.firstName || !x.lastName).length > 0

Or, using some like:

const isEmpty = person.some(x => !x.firstName || !x.lastName);

EDIT:-

function filterItems(TableData) {
  return TableData.filter(function(el) {
    return Object.values(el).some(v => !v);
  })
}
Sign up to request clarification or add additional context in comments.

7 Comments

Use Array#some instead to get rid of the length check
Thanks for prompt response. But in case we need to generalize the code with n number of objects in each array element then?
@palaѕн OP means an arbitrary amount of object values. So person.some(x => Object.values(x).some(val => !val))
I am trying something like this function filterItems(TableData) { return TableData.filter(function(el) { return isEmpty(el); }) } function isEmpty(item) { if(item.length > 0){ return false;//this element is NOT empty }else{ return true;//this element is empty } }
yes sir, works truly smooth. This is of course a generalized function applicable to any array of objects. Thank you.
|
1

You can use forEach to iterate over the array and use Object.values to get all the value. Then use indexOf to test if the value matches.Use a variable to save the state

var person = [{
    firstName: "",
    lastName: "Doe",
    age: 46
  },
  {
    firstName: "John",
    lastName: "",
    age: 35
  }
];

function testArray(arr) {
  var isEmpty = false
  arr.forEach(function(item) {
    if (Object.values(item).indexOf("") !== -1) {
      isEmpty = true
    }

  })
  return isEmpty;
}
console.log(testArray(person))

Comments

1

If at least one item is null or empty, it returns false

const person = [{
  firstName: "",
  lastName: "Doe",
  age: 46
}, {
  firstName: "John",
  lastName: "",
  age: 35
}];

const allItemsHaveValue = person.map(o => Object.values(o).every(v => v)).every(v => v);

console.log('All items have value: ', allItemsHaveValue);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.