简体   繁体   English

如何使用for in循环遍历嵌套对象并返回串联的每个属性字符串?

[英]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. 例如,我想将first,middle和last的属性值打印为连接字符串。

The final output being: "John P. Doe" 最终输出为:“ 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. 使用for-in循环将是一个坏主意,因为不能保证对象保持其顺序。 So you might end up with Doe John P. instead. 因此,您可能最终选择了Doe John P. .。

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 您可以为此使用object.reduce

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. 正如Barmar的答案所暗示的那样,您的示例仅需要简单的串联即可得出结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM