首页 > 解决方案 > 将对象数组转换为数组数组(按属性)

问题描述

我想通过属性“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) => { ... }, [])

如何最好地编写转换?谢谢!

标签: javascriptarraysobjectecmascript-6reduce

解决方案


您可以使用.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; }


推荐阅读