0

I have an array called customers, each customer has a name, id, account number, address and account information:

var customers = [
    {
        "name": "John Doe",
        "id": 1205,
        "accountNumber": 187456,
        "address": {
            "houseNumber": 12,
            "streetName": "made up street",
            "postCode": "WE1 234",
            "area": "Birmingham"
        },
        "hasCurrentAccount": true,
        "hasLoan": false,
        "hasMortgage": true
    },
    {
        "name": "Jane Doe",
        "id": 1304,
        "accountNumber": 123456,
        "address": {
            "houseNumber": 420,
            "streetName": "The Street",
            "postCode": "DE3 456",
            "area": "Wolverhampton"
        },
        "hasCurrentAccount": false,
        "hasLoan": true,
        "hasMortgage": false
    }
];

for now I'm trying to iterate through this array retrieve the name and id and print it to the console:

var info = customers;
for (var i in info)
{
   var id = info.id;
   var name = info.name;
   console.log('Here are your current customers' + id + ' ' + name);
}

but I just get

Here are your current customers undefined undefined

I've tried different methods and I just can't seem to get it working. Can anyone help?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

2 Answers2

0

This will solve your problem.

for (a in customers){
console.log('Here are your current customers' + a + ' ' + customers[a].name);
}
Parth Ghiya
  • 6,929
  • 2
  • 30
  • 37
  • Your post will be much more useful to others if you explain what the problem is and how your solution solves it. *"Try this"* is just an unnecessary statement. – Felix Kling Jan 27 '17 at 15:15
0

You can use the Array.forEach function to iterate through the array. It runs a function on each item, which is where you can log values from the item to the console.

Example:

var customers = [
    {
        "name": "John Doe",
        "id": 1205,
        "accountNumber": 187456,
        "address": {
            "houseNumber": 12,
            "streetName": "made up street",
            "postCode": "WE1 234",
            "area": "Birmingham"
        },
        "hasCurrentAccount": true,
        "hasLoan": false,
        "hasMortgage": true
    },
    {
        "name": "Jane Doe",
        "id": 1304,
        "accountNumber": 123456,
        "address": {
            "houseNumber": 420,
            "streetName": "The Street",
            "postCode": "DE3 456",
            "area": "Wolverhampton"
        },
        "hasCurrentAccount": false,
        "hasLoan": true,
        "hasMortgage": false
    }
];

customers.forEach(function(item) {
  console.log('Here are your current customers', item.id, item.name);
})
Giladd
  • 1,351
  • 8
  • 9