The problem is how to access the attributes of an object. Consider this simple example:
let pessoa = {
idade: 20
};
console.log(pessoa.idade); // 20
console.log(pessoa['idade']); // 20
The object pessoa
has an attribute called "age". And to access it, you can use pessoa.idade
or pessoa["idade"]
- in the first you access the attribute directly, in the second, as a string containing the name of the property between brackets.
Now, if the property name is in a variable, the first form does not work (only the second):
let pessoa = {
idade: 20
};
let nomePropriedade = 'idade';
console.log(pessoa.nomePropriedade); // undefined
console.log(pessoa[nomePropriedade]); // 20
That’s because pessoa.nomePropriedade
is the same as pessoa["nomePropriedade"]
, that is, I am looking for a property whose name is "property name". Only using pessoa[nomePropriedade]
i can get the property whose name is the variable value nomePropriedade
.
So in your case attributes.tipo
is searching for a property called "type" and will not work. Then you would need to use the second option (the variable between brackets, ie, attributes[tipo]
):
let checkOne = [{
"id": 273,
"attributes": {
"humidity": {
"qty": 74.3223333333333,
"unit": "percents"
},
"protein": {
"qty": 23.525,
"unit": "g"
},
"lipid": {
"qty": 1.23766666666667,
"unit": "g"
},
}
}
];
let tipo = 'protein';
let resultado = (typeof checkOne[0].attributes[tipo] !== 'undefined');
console.log(resultado); // true
but in my case I need to check more than one property.
– Luh
let’s say I need to check 100 properties, if it’s by that logic I’d have to write checkOne.some(item=>item.attributes.propX) 100 times
– Luh