0

How would I print/log the name and age of each user using a for loop?

var users = [
  {name: "Michael", age:37},
  {name: "John", age:30}, 
  {name: "David", age:27}
];

I've tried setting a for loop to get the name and age but I just log the object

var users = [
  {name: "Michael", age:37},
  {name: "John", age:30}, 
  {name: "David", age:27}
];

var i, len, text;

for (i = 0, len = users.length, text = ""; i < len; i++)
{
    text += users[i] + "<br>";
}

Expected Result:

Michael - 37
John - 30
David - 27

How can I get that output?

1
  • 1
    What language? I'm guessing JavaScript, but figured I'm ask. Commented Feb 16, 2019 at 2:55

2 Answers 2

5

At the moment you are only looping through your array. Thus users[i] will give you a particular object in your array.

So, if you want to get the name and age of a given object you can use dot notation:

  • users[i].name to get the name of the ith object

  • users[i].age to get the age of the ith object

Also, since your string that you're building (text) includes HTML (<br />), I assume you want to add the result of it to the page (and not print it to the console). You can do this by using:

document.body.innerHTML += text

This will add your text string as HTML to the body of your HTML.

See working example below:

var users = [{
    name: "Michael",
    age: 37
  }, {
    name: "John",
    age: 30
  },
  {
    name: "David",
    age: 27
  }
];

var text = "";
for (var i = 0; i < users.length; i++) {
  var name = users[i].name; // get the name
  var age = users[i].age; // get the age
  text += name + " - " +age + "<br>";
}

document.body.innerHTML = text; // add the text to the page

Also, if you wish, once you become comfortable with loops and such you can use functional programming, ES6 destructing and template literals to achieve the same task:

const users = [{name: "Michael", age: 37}, {name: "John", age: 30}, {name: "David", age: 27}],

text = users.reduce((acc, {name, age}) => `${acc}${name} - ${age}<br />`, ``);
document.body.innerHTML = text; // add the text to the page

Sign up to request clarification or add additional context in comments.

Comments

2

Another complementary alternative to the answer given by Nick Parsons could be using Array.map() and Array.join():

const users = [
  {name: "Michael", age: 37},
  {name: "John", age: 30},
  {name: "David", age: 27}
];

let text = users.map(({name, age}) => `${name} - ${age}`).join("<br>");

document.body.innerHTML += text;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.