使用 JavaScript 如何递归地从数组中删除对象并将这些项目添加到新数组中?

问题描述 投票:0回答:1

我有一个嵌套对象数组:

const members = [
  {
    name: 'Mike',
    type: 'MANAGER',
    children: []
  },
  {
    name: 'John',
    type: 'MANAGER',
    children: [
      {
        name: 'George',
        type: 'EMPLOYEE',
        children: []
      },
      {
        name: 'Jake',
        type: 'EMPLOYEE',
        children: []
      },
      {
        name: 'Fred',
        type: 'MANAGER',
        children: [
          {
            name: 'Henry',
            type: 'EMPLOYEE',
            children: []
          },
          {
            name: 'Julie',
            type: 'MANAGER',
            children: []
          }
        ]
      }
    ]
  },
  {
    name: 'Alex',
    type: 'MANAGER',
    children: [
      {
        name: 'Mark',
        type: 'EMPLOYEE',
        children: []
      },
      {
        name: 'Ashley',
        type: 'MANAGER',
        children: []
      }
    ]
  }
];

如何递归地从数组中删除所有

EMPLOYEE
对象并将它们添加到新数组中?

我可以将所有

EMPLOYEE
成员添加到新数组中,但我不确定如何从原始数组中删除它们。

const employees = [];

const extractEmployees = (members) => {
  for(let i = 0; i < members.length; i++) {
    const member = members[i];

    // add employee to employees array
    if(member.type === 'EMPLOYEE') {
      employees.push(member);
    }

    if(member.children) {
      // call function recursively for member children
      extractEmployees(member.children);
    }
  }
}

// initialize
extractEmployees(members);
javascript arrays recursion filter
1个回答
0
投票

extractEmployees
可以返回不包含员工的新成员数组 (
newMembers
)。该数组被分配给
member.children
:

const employees = [];

const extractEmployees = (members) => {
  const newMembers = []; // init a new array

  for(let i = 0; i < members.length; i++) {
    const member = members[i];

    if(member.type === 'EMPLOYEE') {
      employees.push(member);
    } else { // if not employee add it to newMembers
      newMembers.push(member);
    }

    if(member.children) {
      // assign the returned array of members to current children
      member.children = extractEmployees(member.children);
    }
  }
  
  return newMembers; // return the new array of members
}

const members = [{"name":"Mike","type":"MANAGER","children":[]},{"name":"John","type":"MANAGER","children":[{"name":"George","type":"EMPLOYEE","children":[]},{"name":"Jake","type":"EMPLOYEE","children":[]},{"name":"Fred","type":"MANAGER","children":[{"name":"Henry","type":"EMPLOYEE","children":[]},{"name":"Julie","type":"MANAGER","children":[]}]}]},{"name":"Alex","type":"MANAGER","children":[{"name":"Mark","type":"EMPLOYEE","children":[]},{"name":"Ashley","type":"MANAGER","children":[]}]}];

// initialize
extractEmployees(members);

console.log(members);

© www.soinside.com 2019 - 2024. All rights reserved.