I want to make a general function where I can print a chosen property from an array with objects.
http://jsbin.com/iNOMaYo/1/edit?js,console,output
Example:
var contacts = [
{
name: 'John',
address:{
country:'Germany',
city:'Berlin'
}
},
{
name: 'Joe',
address:{
country:'Spain',
city:'Madrid'
}
}
]
And this is my function:
function print(array, key, index){
console.log(array[index][key]);
}
So if I want the name for example:
print(contacts, 'name', 0)
I get 'John'.
But how do I do if i want the city instead?
This gets undefined:
print(contacts, 'address.city', 0)
http://jsbin.com/iNOMaYo/1/edit?js,console,output
Any ideas?