【问题标题】:JavaScript : Optimal solution to filtered out the objects from an array based on the n-level nested property valueJavaScript:基于 n 级嵌套属性值从数组中过滤掉对象的最佳解决方案
【发布时间】:2022-11-14 07:47:55
【问题描述】:

要求:是否有任何最佳或简单的方法可以根据其值从包含特定属性的数组中过滤掉对象,而无需递归.

问题陈述:我们可以在递归的帮助下实现这个要求,但是由于数据集(对象数组)非常大并且每个对象包含n个嵌套对象,递归方法会导致性能问题。

这是示例模拟数据:

[{
  children: [{
    children: [{
      children: [],
      isWorking: 'yes'
    }]
  }]
}, {
  children: [],
  isWorking: 'no'
}, {
  children: [{
    children: [{
      children: [],
      isWorking: 'no'
    }]
  }]
}, {
  children: [{
    children: [],
    isWorking: 'yes'
  }]
}, ...]
  • 我想从包含嵌套isWorking 属性的数组中过滤掉根对象,其值为yes
  • isWorking 属性仅适用于不包含子对象的对象。即children: []

正如我之前所说,我可以通过递归来实现这一点,但要寻找一个不会影响性能的最佳解决方案。

这是我尝试过的(工作解决方案):

const parent = [{
  children: [{
    children: [{
      children: [],
      isWorking: 'yes'
    }]
  }]
}, {
  children: [],
  isWorking: 'no'
}, {
  children: [{
    children: [{
      children: [],
      isWorking: 'no'
    }]
  }]
}, {
  children: [{
    children: [],
    isWorking: 'yes'
  }]
}];

const isWorkingFlagArr = [];

function checkForOccupation(arr) {
  arr.forEach(obj => {
    (!obj.children.length) ? isWorkingFlagArr.push(obj.isWorking === 'yes') : checkForOccupation(obj.children)
  })
}

checkForOccupation(parent);

const res = parent.filter((obj, index) => isWorkingFlagArr[index]);

console.log(res);

【问题讨论】:

  • 是你吹堆栈的“性能问题”吗?

标签: javascript arrays object recursion


【解决方案1】:

以下是尝试将每个递归调用放在一个新的微任务上,从而避免爆栈。

不确定这是否符合您的要求。

(async () => {
  const getFlags = async (arr) => {
      const flags = []

      const checkForOccupation = async (arr) => {
          for(const { children, isWorking } of arr) {
              !children.length
                  ? flags.push(isWorking === 'yes') 
                  : await checkForOccupation(children) 
          }
      }

      await checkForOccupation(arr)

      return flags
  }

  const data = [{
    children: [{
      children: [{
        children: [],
        isWorking: 'yes'
      }]
    }]
  }, {
    children: [],
    isWorking: 'no'
  }, {
    children: [{
      children: [{
        children: [],
        isWorking: 'no'
      }]
    }]
  }, {
    children: [{
      children: [],
      isWorking: 'yes'
    }]
  }]

  const flags = await getFlags(data)
  console.log(data.filter((_, index) => flags[index]))
})()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 2020-11-07
    • 1970-01-01
    • 2021-08-01
    • 2017-06-29
    • 2016-11-17
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多