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
.
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
– Bacco
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']);
– Augusto Vasques
It will work with "key" if you remove the quotes: console.log(json[0][key]);
– Bacco
@Bacco, it took me a while to understand...
console.log(json[0][key]);
beingkey
the parameter containing the stringid
.– Augusto Vasques
"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.
– Bacco