How to check an object type attribute in Javascript?

Asked

Viewed 312 times

7

I get the following object:

obj = {
    fernando: {
        nome: 'Fernando',
        idade: 21
    },
    tiago: {
        nome: 'tiago',
        idade: NaN
    },
    total: 2
}

As you can see, I receive an object where each attribute can be another object, and it can also be an attribute of the whole type.

How do I check each "person". age is Number????

EDIT: I need to check "N" values (people), not just a specific one...

2 answers

5

You can iterate the object keys using Object.Keys and check if it is a number using isNaN:

var obj = {
  fernando: {
    nome: 'Fernando',
    idade: 21
  },
  tiago: {
    nome: 'tiago',
    idade: NaN
  },
  lucas: {
    nome: 'Lucas',
    idade: 23
  },
  total: 2
};

Object.keys(obj).forEach(function(key) {
  if (!isNaN(obj[key].idade))
      console.log(obj[key].nome + " possui idade");
});

5


To access the properties of an object you can do it in two ways:

var obj = {
    fernando: {
        nome: 'Fernando',
        idade: 21
    },
    tiago: {
        nome: 'tiago',
        idade: NaN
    },
    total: 2
};

console.log(obj.tiago.nome); // dá tiago
console.log(obj['tiago']['nome']); // dá tiago

Both work but the first is more used when you know the name of the property beforehand.

To know the type of the variable/property you can use the typeof:

console.log(typeof 0); // number
console.log(typeof 4); // number
console.log(typeof NaN); // number
console.log(typeof 'texto'); // string

If you add to that object methods you can find what you need:

var obj = {
    fernando: {
        nome: 'Fernando',
        idade: 21
    },
    tiago: {
        nome: 'tiago',
        idade: NaN
    },
    total: 2
};

// quantos têm idade válida
var nrValidos = Object.keys(obj).filter(nome => obj[nome].idade).length;
console.log(nrValidos); // 1

// quantas pessoas têm a propriedade idade
var nrEntradas = Object.keys(obj).filter(nome => obj[nome].hasOwnProperty('idade')).length;
console.log(nrEntradas); // 2

// quais as pessoas que têm a propriedade idade válida
var nomes = Object.keys(obj).filter(nome => obj[nome].idade);
console.log(nomes); // ["fernando"]

If you only check obj[nome].idade gives false to NaN and 0. If you want to distinguish them you can use isNaN. isNaN(NaN) //dá true

  • Sergio, have you been using Arrow functions without transposing the code? This is already reasonably supported?

  • 1

    @bfavaretto by chance do not know if the IE11 supports (I imagine not), the others I think already support. As I work in an environment that is transposed by Babel I have made it a habit to use ES6+.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.