【发布时间】:2018-10-29 08:48:24
【问题描述】:
我有一些来自 Angular 的经典服务的数据,看起来像这样(简要地):
const obj = {
field: [
{
id: 1,
items: []
},
{
id: 2,
items: [ { wateva: 'wateva1' } ]
},
{
id: 3,
items: false
},
{
id: 4,
items: [ { yeah: 7 } ]
}
]
}
好吧,我的任务只是收集所有不为空的数组项。 我的解决方案(实际上我的解决方案是用 TypeScript 和 Angular 5 编写的,但为了让它更简单易懂,它会像......):
function getItems() {
const items = [];
obj.field.forEach(currentField => {
if (currentField.items && currentField.items.length) {
currentField.items.forEach(currentItem => items.push(currentItem));
}
});
return items;
}
是的,它非常简单,并且可以按预期工作(当前的将返回...):
[ { wateva: 'wateva1' }, { yeah: 7 } ]
现在我的问题...如何使我的解决方案发挥作用?我想摆脱我的新变量items,我不想推入那个变量,我只想在一个动作中返回结果。任何帮助将不胜感激。
P.S.不接受第三图书馆的建议:)
【问题讨论】:
标签: javascript arrays angular function functional-programming