0

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?

Joe
  • 4,274
  • 32
  • 95
  • 175

3 Answers3

2
function print(array, key, index){
  var parts = key.split(".");
  var returnValue = array[index];
  for(var i=0;i<parts.length;i++) {
    returnValue = returnValue[parts[i]];
  }
  console.log(returnValue);
}
Dominik Goltermann
  • 4,276
  • 2
  • 26
  • 32
0

Best thing I could come up at the moment:

http://jsbin.com/iziFevIg/1/edit?html,js,output

Maybe someone else has a better idea.

0

My solution is pretty naive, I haven't thought about it in the edge cases but I'm a fan of functional programing so this immediately (leaving immutability aside)

function print(array, key, index) {
  var splitted_key, new_key;

  if (key.indexOf(".") !== -1) { 
    splitted_key = key.split(".");
    new_index = splitted_key.shift();
    new_key = splitted_key.join(".");
    print(array[index], new_key, new_index);
  }
  else {
    console.log(array[index][key]);
  }
}

http://jsbin.com/IFeciJIz/2/edit

gmaliar
  • 5,294
  • 1
  • 28
  • 36