Check whether an item exists within an array, using a variable

Asked

Viewed 125 times

0

Let’s say I have this array:

let checkOne = [
{
"id": 273,
"attributes": {
"humidity": {
"qty": 74.3223333333333,
"unit": "percents"
},
"protein": {
"qty": 23.525,
"unit": "g"
},
"lipid": {
"qty": 1.23766666666667,
"unit": "g"
},
}
}];

I want through the variable guy check if the contents in the array exist within the array:

//Tentava
let tipo = 'protein'
let resultado = (typeof checkOne[0].attributes.tipo !== 'undefined');

console.log(resultado) //era para retornar true, mas aparece false

3 answers

1


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

1

Hello!

If you try to access the attribute this way checkOne[0].attributes.tipo, you are trying to access the type variable within the attributes, and will always give false.

If you need to access an object attribute dynamically, you need to access it with brackets:

let tipo = 'protein';
checkOne[0].attributes[tipo] // js vai interpretar como checkOne[0].attributes.protein

Then you can use this to create a function and check if the item has the attribute.

function possuiTipo(item, tipo) {
    return item.attributes[tipo] !== undefined; // se existir retornará true;
}

If you want to know what all the items have this type, you can use the function filter() together with the previous function.

const tipo = "protein";
const resultado = checkOne.filter(item => {
    return possuiTipo(item, tipo)
});

0

That condition typeof checkOne[0].attributes.tipo !== 'undefined' will always be false, because there is no property tipo inside attributes, that is to say, attributes.tipo is undefined.

In addition you can directly check the property protein using the function some:

checkOne.some(item=>item.attributes.protein) // return true se ao menos um elemento possui attributes.protein
  • but in my case I need to check more than one property.

  • 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

Browser other questions tagged

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