How do I use a variable instead of the Array key?

Asked

Viewed 229 times

2

I’m new to JSON manipulation. have an Array:

let json = [
    {
        "id": 111111,
        "name": "nome1"
    },{
        "id": 222222,
        "name": "nome2"
    }
]

How do I pass the key name as a function parameter?

Example:

teste = (json, key) => {
    console.log(json[0].key); // "key" é minha variável, que vai receber a string "id"
}

teste(json, 'id');

I want in this case above to return 111111.

teste(json, 'name');

And in this case above return name1.

  • 2

    That’s not a JSON, it’s a Javascript object, it’s very different things. And there is no way you can use a "key" property if there is no "key" in the object (after all, you only have the numeric positions, and the keys "id" and "name". Important [Dit] the post and clarify better which difficulty exactly (if that’s what I said, what result I expected, these things). - If you want to use the variable, put it between brackets

  • 1

    If it is the id of one of the elements of the array you want to use should look something like this: console.log(json[0]['id']);

  • It will work with "key" if you remove the quotes: console.log(json[0][key]);

  • @Bacco, it took me a while to understand... console.log(json[0][key]); being key the parameter containing the string id.

  • "Cris and Rafa, "I edited the question to try to make it clearer, make sure it’s correct. PS: If you are two people, create separate accounts. The rules of the site do not allow collective accounts.

1 answer

4

The problem is that you are using ". key" literally, so you are referring to a "key" element:something that doesn’t exist.

Use variable as index (no quotes) to solve:

var objeto = [
    {
        "id": 111111,
        "name": "nome1"
    },{
        "id": 222222,
        "name": "nome1"
    }
]

var key = "id";

console.log(objeto[0][key]); //sem aspas, "key" é variável

console.log(objeto[0]['id']); //com aspas, "id" é a chave

console.log(objeto[0].id); //literal

Important remark: What you have in the code is a object and not a JSON. JSON is a String in "JS object format", it is a specification. The Object is already a language structure.

Browser other questions tagged

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