javascript - 使用javascript将数组重组为数组数组
问题描述
我试图将数组插入数组,例如我有
var objList = [
{
name: jack,
status: ''
},
{
name: mark,
status: yes
},
{
name: erik,
status: no
},
{
name: mike,
status: yes
},
{
name: chaze,
status: no
}
]
我想要的是每次找到“状态:是”时,它都会将其推送到具有以下“状态:或”的新数组。它看起来像这样
[[{name: jack, status: ''}], [{name: mark, status: yes},{name: erik, status: no}], [{name: mike, status: yes},{name: chaze, status: no}]]
解决方案
您可以减少数组并检查状态是否为yes
,然后将新的子数组添加到结果集中。然后只需将对象添加到最后一个数组。
var data = [{ name: 'jack', status: '' }, { name: 'mark', status: 'yes' }, { name: 'erik', status: 'no' }, { name: 'mike', status: 'yes' }, { name: 'chaze', status: 'no' }],
result = data.reduce((r, o) => {
if (!r.length || o.status === 'yes') {
r.push([]);
}
r[r.length - 1].push(o);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- java - 我的应用程序跳过启动意图并执行下一行代码?
- typescript - 检测 Word 上的更改(API Office)
- powershell - 导入 .csv AzureADUser 脚本仅返回 100 个条目
- solidity - windows10无法安装web3 js
- internet-explorer - 剑道网格过滤器值
- python-3.x - Bigquery CSV 文件加载失败
- node.js - 在Nodejs上加密角度解密数据
- function - Regina Rexx 中的外部函数如何返回数据?
- regex - 使用正则表达式查找整个 json 元素
- mysql - MySQL:显式主机名与带有通配符的主机名