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'
};
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.
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);
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
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(' '));
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);
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]);
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.