首页 > 解决方案 > 使用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}]]

标签: javascriptnode.js

解决方案


您可以减少数组并检查状态是否为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; }


推荐阅读