I am looping data in JQuery, and I want to retrieve a specific key from an array
So I tried this code inside the loop to get the key from a value returned in the loop
data[i].dns_types[ data[i].type ]
But that doesn’t work, I created a fiddle below to recreate my code.
Getting the value of dns_types[ data[i].type ]
returns the correct value from the array
https://jsfiddle.net/h7cgbyqt/
>Solution :
- Your
dns_types
is string, so you need to parse it as JSON - You must use
data
anddns_types
as two separate variables
var dns_types = '{"A":"ip","AAAA":"ipv6","CNAME":"target","MX":"","TXT":"","SRV":"","NS":""}';
var dnsTypesJson = JSON.parse(dns_types);
var data = [
{
"target": "1.2.3.5",
"ref": 56283838,
"host": "www.computerbuilder.co.uk",
"type": "CNAME"
},
{
"target": "129.0.0.1",
"ref": 56283838,
"host": "www.computerbuilder.co.uk",
"type": "CNAME"
}
];
for(var i in data) {
let subData = data[i];
let type = dnsTypesJson[subData.type];
alert(subData[type]);
}