var test = {a:'a',b:{a:'good',c:{c:'practice'}}}
谢谢!
答案 0 :(得分:1)
因为您不知道对象是如何嵌套的,所以您需要使用递归来完成手头的任务。您无法在对象本身上使用.reduce
,因此您必须使用Object.keys
从对象中获取属性数组。然后你可以.reduce
返回的数组。
var test = {a:'a',b:{a:'good',c:{c:'practice'}}};
var deeperTest = {a:'a',b:{a:'deeper',b:{a:'test',b:{a:'than',b:{a:'before'}}}}};
function reducer(obj) {
if (typeof obj != 'object') return ''; //we only want to reduce 'objects'
return Object.keys(obj).reduce(function(prev, curr) {
if (typeof obj[curr] != 'string')
prev += ' ' + reducer(obj[curr]); //probably an object - let's dig in
else
prev += ' ' + obj[curr]; //just a string - append to accumulator
return prev;
}, "");
}
console.log(reducer(test));
console.log(reducer(deeperTest));