【问题标题】:Combine unknown sub-arrays of objects from an array of objects and filter it从对象数组中组合未知的对象子数组并过滤它
【发布时间】:2021-11-02 08:11:26
【问题描述】:

一种更简单的方法来重新创建此代码的输出,如果 sub arr0 不为空,它会组合它并通过键 code 过滤所需的输出。

提前谢谢你!

let array = [
  {
    id: 1,
    text: 'stuff1',
    arr0: [
      {id:1, code: 'imacode1'},
      {id:2, code: 'imacode2'},
    ]
  },
  {
    id: 2,
    text: 'stuff2',
    arr0: [
      {id:3, code: 'imacode3'},
      {id:4, code: 'imacode4'},
    ]
  },
  {
    id: 3,
    text: 'stuff3',
    arr0: []
  }
]
let arr = [];

for(let i of array){
  if(i.arr0.length !== 0){
    arr.push(i.arr0)   
  }
}
arr = arr.flat()
for(let j of arr){
  if(j.code === 'imacode2'){
    let code = arr.filter(j=>j.code!=='imacode2')
    code = code.map(({code}) => code)
    console.log(code)
  }
}
    

编辑:添加了 sn-p

【问题讨论】:

    标签: javascript arrays json


    【解决方案1】:

    您可以使用 Array.flatMap()Array.filter() 来获得您想要的结果,首先我们使用 .flatMap() 创建一个数组,其中包含每个 arr0 中的所有项目。

    然后我们使用 .filter() 仅包含所需的项目,使用自定义(可修改)过滤器函数,在这种情况下删除任何代码为“imacode2”的项目。

    let array = [ { id: 1, text: 'stuff1', arr0: [ {id:1, code: 'imacode1'}, {id:2, code: 'imacode2'}, ] }, { id: 2, text: 'stuff2', arr0: [ {id:3, code: 'imacode3'}, {id:4, code: 'imacode4'}, ] }, { id: 3, text: 'stuff3', arr0: [] } ]
    
    // Change filter as desired..
    const filterProc = ({id, code}) => code !== 'imacode2';
    const result = array.flatMap(el => el.arr0 || []).filter(filterProc).map(({code}) => code);
    console.log(result)
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 它可以工作,谢谢,并且只为我刚刚添加到另一个地图中的代码获取结果,就像这样,var x = result.map(({code})=>code)
    • 我也会更新答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2020-07-11
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多