有人把这个问题作为练习题交给了我。我必须在以下对象上使用“_.reduce”来打印出文本“a good practice”。坦率地说,我什至都在努力在脑海中想象这一点。任何帮助,将不胜感激。
var test = {a:'a',b:{a:'good',c:{c:'practice'}}}
谢谢!
最佳答案
因为您不知道对象是如何嵌套的,所以您需要使用递归来完成手头的任务。您不能对对象本身使用 .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));
关于javascript - 在嵌套对象上使用 reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40920386/