0

how do i print out all the person in the person object?

For Example i want my output to be like this.

John Doe 25

Paul Vosper 23

 var txt = "";
 var person = {
            p1: {fname:"John", lname:"Doe", age:25},
            p2: {fname:"Paul", lname:"Vosper", age:23}
           }; 
  var x;
  for (x in person) 
  {
    txt += person[x] + " ";
  }
  document.getElementById("demo").innerHTML = txt;

2 Answers 2

3

You can do a map/join:

var txt = Object.keys(person).map(function(k) {
  var p = person[k];

  return [p.fname, p.lname, p.age].join(' ');
}).join(' ');

Output in the console:

output

If you want a line break element (<br>) between them, just join on a <br>:

document.getElementById("demo").innerHTML = Object.keys(person)
                                            .map(combineAllProperties)
                                            .join('<br>');

function combineAllProperties(k) {
  var p = person[k];

  return [p.fname, p.lname, p.age].join(' ');
}
Sign up to request clarification or add additional context in comments.

2 Comments

so the only way to do it is to write a separate function to combine and print it? you cant just iterate an object in an object and print?
@Mebighobo, you can just iterate and print, but the way I've suggested is a semantic programming paradigm (the algorithm you're trying to implement is fundamentally a map/join, and JavaScript supplies those methods out of the box). It's not a "separate" function, it's a callback to the map method.
1

You can use Array.prototype.reduce in conjunction with Object.keys:

var person = {
  p1: {fname:"John", lname:"Doe", age:25},
  p2: {fname:"Paul", lname:"Vosper", age:23}
};

document.write(Object.keys(person).reduce(function(s, p, i) {
  var o = person[p];
  return s + (i>0?'<br>':'') + o.fname + ' ' + o.lname + ' ' + o.age
  }, '')
);

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.