Home > OS >  Find out if the values of an object inside an array that is itself a value of a parent object are tr
Find out if the values of an object inside an array that is itself a value of a parent object are tr

Time:11-06

I am trying to validate information entered by a user and make sure none of the strings are empty.

Some of that information can be added into an array as "extra users" also joining the group.

So the data can look something like this:

const userInfo = {
  firstName: 'Jimmy',
  lastName: 'Hendrix',
  extraUsers: [{
    firstName: 'Bob',
    lastName: 'Michael'
  }],
};

And this is what I run to check for any empty strings in the 'extraUsers' Array:

function checkForEmptyStrings() {
  return (
    userInfo.extraUsers.every((extraUser) => {
      Object.values(extraUser).every((x) => x !== '')
    })
  );
}

console.log(checkForEmptyStrings())

The output I get is false but I'd expect it to be true since none of the strings are empty. Actually if I console.log Object.values(extraUser).every((x) => x !== '') I get true

Why do I get false as a final result?

There's probably another way to do this, but for research purposes I'm curious to know what is going on here.

Cheers and happy coding

CodePudding user response:

You need to return the inner every

const userInfo = {
  firstName: 'Jimmy',
  lastName: 'Hendrix',
  extraUsers: [{
    firstName: 'Bob',
    lastName: 'Michael'
  }],
};
// And this is what I run to check for any empty strings in the 'extraUsers' Array:

function checkForEmptyStrings() {
  return (
    userInfo.extraUsers.every((extraUser) => {
      return Object.values(extraUser).every((x) => x )
    })
  );
}

console.log(checkForEmptyStrings())

  • Related