1

For example i want to print the property values of first, middle, and last as concatenated strings.

The final output being: "John P. Doe"

var  person = {
    name: {
        first: 'John',
        middle: 'P',
        last: 'Doe'
    },
    age: 35,
    homeTown: 'Nashville, TN'
};
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
trenov
  • 35
  • 8

6 Answers6

2

You don't need a loop, just concatenate the properties.

var fullname = person.name.first + ' ' + person.name.middle + ' ' + person.name.last;

Using a for-in loop would be a bad idea, because objects aren't guaranteed to maintain their order. So you might end up with Doe John P. instead.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks Barmar !! Pretty new to programming. Didn't realize i could concatenate them. This was very useful ! – trenov Nov 21 '16 at 03:17
0

these type of questions have been posted millions of times, do some research before asking.

anyway:

alert(person.name.first + ' ' + person.name.middle + ' ' + person.name.last);
Paolo
  • 704
  • 9
  • 24
0

you can use object.reduce for this

check this snippet

var person = {
  name: {
    first: 'John',
    middle: 'P',
    last: 'Doe'
  },
  age: 35,
  homeTown: 'Nashville, TN'
};


var nameObject = person.name;

var fullname = Object.keys(nameObject).reduce(function(previous, key) {
  return previous +" "+ nameObject[key];
}, "");

console.log(fullname);

Hope it helps

Geeky
  • 7,420
  • 2
  • 24
  • 50
0

You could use an array for the wanted property names (this keeps the order) and map the values and join it to a space separated string.

var  person = { name: { first: 'John', middle: 'P', last: 'Doe' }, age: 35, homeTown: 'Nashville, TN' };

console.log(['first', 'middle', 'last'].map(function (k) {
    return person.name[k];
}).join(' '));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use destructuring assignment

var  person = {
    name: {
        first: 'John',
        middle: 'P',
        last: 'Doe'
    },
    age: 35,
    homeTown: 'Nashville, TN'
};

var {first, middle, last} = person.name;

var fullname = `${first} ${middle} ${last}`;

console.log(fullname);
guest271314
  • 1
  • 15
  • 104
  • 177
0

As Barmar's answer suggests, your example only needs a simple concatenation to give you your results.

However, in the more general case, you would want to iterate through each property of an object, and if the property is an object, iterate through that object as well.

For instance:

function iterateThroughAllProperties(obj) {
    Object.keys(obj).forEach(function(key, index) {
        if(typeof obj[key] !== null && typeof obj[key] === 'object') {
            iterateThroughAllProperties(obj[key]);
        }
        else {
            // Do something with the property.
            console.log(obj[key]);
        }
    });
}
  • Thanks Sesh! I was thinking along the lines of this solution before i realize how simple it was. I will most definitely study it. – trenov Nov 21 '16 at 03:22