如何使我的JS解决方案正常运行?



我有一些来自 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 } ]

现在我的问题...如何使我的解决方案正常运行?我想摆脱我的新变量,我不想推入该变量,我只想在一个操作中返回结果。任何帮助将不胜感激。

附言不接受对第三个库的建议:)

如果你可以使用 es6(既然你提到你正在使用打字稿,那应该没问题(,你可以通过组合concatmapfilter和 spread 运算符来把它变成一个不错的函数单行代码:

const obj = {
field: [
{
id: 1,
items: []
},
{
id: 2,
items: [ { wateva: 'wateva1' } ]
},
{
id: 3,
items: false
},
{
id: 4,
items: [ { yeah: 7 } ]
}
] 
}
function getItems(obj) {
return [].concat(...obj.field.map(o => o.items).filter(Array.isArray))
}
console.log(getItems(obj))

您可以使用flatMap(阶段3(。flatMap这里符合幻想之地的chain规格。

data.field.flatMap
(({ items }) =>
Array.isArray (items) ? items : []
)
// [ { wateva: 'wateva1' }, { yeah: 7 } ]

您可以在没有它的环境中填充它

Array.prototype.flatMap = function (f) {
return this.reduce
( (acc, x) =>
acc.concat (f (x))
, []
)
}

完整程序演示

Array.prototype.flatMap = function (f) {
return this.reduce
( (acc, x) =>
acc.concat (f (x))
, []
)
}
const data = 
{ field:
[ { id: 1, items: [] }
, { id: 2, items: [ { wateva: 'wateva1' } ] }
, { id: 3, items: false }
, { id: 4, items: [ { yeah: 7 } ] } 
]
}
const result =
data.field.flatMap
(({ items }) =>
Array.isArray (items) ? items : []
)
console.log (result)
// [ { wateva: 'wateva1' }, { yeah: 7 } ]

您可以使用Array.reduce和点差运算符累加到空数组中:

obj.field.reduce(
(acc, current) => current.items && current.items.length > 0 ? [...acc, ...current.items] : acc, [])
);

使用 Array.prototype.reduce、对象解构和扩展赋值:

function getItems({ field }) {
return field.reduce((result, { items }) => 
items instanceof Array ? 
items.reduce((items, item) => [...items, item], result) :
result
, []);
}

相关内容

最新更新