Browse JSON with Javascript objects

Asked

Viewed 264 times

-3

Good night, you guys. I’m starting in JS with VUE.. I have a situation that I could not solve:

I have 1 JSON object with 2 objects that come as a return:

retorno = {
obj1 =    {
    "permitido":false,
    "msg": "erro"
}, 
obj2 = {
    "permitido":true,
    "msg": "ok"
} 
}

How do I go through/map and test the "allowed" key for all the elements that came? When the return was just an object, I mapped it like this:

Object.values(retorno['obj1'].map(elm => {}...

Can you help me?

1 answer

0

You can use Object.keys() to get all the Keys coming in JSON, and then use a for to traverse these objects.

var json = {
    "obj1": {
        "permitido": false,
        "msg": "erro"
    },
    "obj2": {
        "permitido": true,
        "msg": "ok"
    }
}

var keys = Object.keys(json)
for (key in keys){
    if (json[keys[key]].permitido){
        console.log(`Sucesso! (${keys[key]}) = ${json[keys[key]].msg}`)
    } else {
        console.log(`Erro! (${keys[key]}) = ${json[keys[key]].msg}`)
    }
}

  • Okay. I get the logic. But I don’t think it’s gonna work. It is because in this return if at least one of the objX has allowed = false, you should not complete the transaction and present the message that came in that objX.

  • If you don’t want the message to appear when permitido = false, just don’t add the else.

  • All right! Thank you

Browser other questions tagged

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