javascript - 将对象数组转换为数组数组(按属性)
问题描述
我想通过属性“icon”将我的数组转换为数组数组。
const array = [
{ icon: true },
{ icon: false },
{ icon: false },
{ icon: true },
{ icon: false }
]
我需要:
[[{icon: true}, {icon: false}, {icon: false}], [{{icon: true}, {icon: false}}]]
属性icon === true
是新数组开始形成的标志。
我认为你应该使用reduce函数。
array.reduce((result, item, index) => { ... }, [])
如何最好地编写转换?谢谢!
解决方案
您可以使用.reduce()
以下方法:
const data = [{ icon: true }, { icon: false }, { icon: false }, { icon: true }, { icon: false }]
const result = data.reduce((r, c) => {
if(c.icon === true)
r.push([c]);
else
r[Math.max(r.length - 1, 0)].push(c);
return r;
},[]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- c# - Blazor WASM 基于查询字符串授权属性
- string - lua拆分字符串并保存在lua表中
- sql - 尝试插入表时违反完整性约束错误
- python-3.x - 如何将自定义对象分配给 xarray 数据值?
- javascript - 在 React 中第一次使用 Axios 没有错误时进行第二次 api 调用
- java - 让冒泡排序更高效
- java - 使用 TNS 连接到外部 Oracle 数据库
- r - 用 NA 创建虚拟变量的更好方法-尝试改进编码我已经做得很差了
- python - 如何使用 tf.function 从 TensorFlow 中的一组函数中随机选择
- javascript - 使用带有故事书和角度的全局样式表 - SassError: SassError: expected "{"