trenov
trenov

Reputation: 35

How can i loop through a nested object, using the for in loop and return each property string concatenated?

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'
};

Upvotes: 1

Views: 62

Answers (6)

Sesh Sadasivam
Sesh Sadasivam

Reputation: 39

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]);
        }
    });
}

Upvotes: 0

guest271314
guest271314

Reputation: 1

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);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386883

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(' '));

Upvotes: 0

Geeky
Geeky

Reputation: 7496

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

Upvotes: 0

Paolo
Paolo

Reputation: 734

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);

Upvotes: 0

Barmar
Barmar

Reputation: 782785

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.

Upvotes: 2

Related Questions