javascript - How to get rid of an intermediate array in this case?
问题描述
I have this this function (I think the code is self-explanatory):
items: function(input) {
let arr = [];
for(let i=0; i<input.length; i++){
if(input[i].quantity > 0) {
arr.push({
value: false,
name: input[i].name,
});
}
}
return arr;
},
I wonder if there is a shorter way to do it without relying on the intermediate arr
?
解决方案
我会使用 Array 内置方法:
items: (input) => input
.filter(({ quantity }) => quantity > 0)
.map(({ name }) => ({ name, value: false }))
推荐阅读
- android - 打开对话框时使用后台活动
- php - 慢速搜索查询WordPress
- azure - Azure 服务总线主题跨订阅缺少数据
- python - 如何使用 Flask 检查开发服务器是否已经在端口上运行?
- c# - 从 Lambda 调用时,S3 GetObjectAsync 间歇性挂起
- java - 使用来自 IBM MQ 的所有消息
- javascript - Html.DevExtreme.Popup 中的 JavaScript 不更新计时器/计数器文本
- javascript - 如何添加过渡持续时间以切换 CSS 类
- windows - 将文件路径传递给 Windows 中的自定义 URI 处理程序
- asciidoc - 等宽格式文本中的最后一个字符为空白