Return 来自重新排列文字对象数组的递归函数的对象

Return object from a recursive function that rearranges array of literal objects

我有一个将文字对象作为输入的函数。 结果它应该 return 2 个对象数组。

它是一个递归函数,所以 return 发生在第 n 个递归周期,数据如下:

//code
const filterObject = (object, array1 = null, array2 = null) => {
let a1 = array1 === null?[]: array1; //array1 is passed as a part of recursion and when recursed is not null
let a2 = array2 === null?[]: array2; //same here
...
//some filtering and object manipulation to create **composedObject**
...
if (condition x is met){
a1.push(composedObject)
}
if( condition y is met ){
a2.push(composedObject)
...
//filtering out parts of initial object that were used
//what is left is assembled into **untreatedObject**
...
if (there are still parts of the initial object that are left untreated){
 filterObject(untreatedObject, a1, a2); //here recursion happens and we pass these arrays there as well as they will continue to be populated
}
else if (everything is filtered and objects are ready){
console.log(a1) //values are present and correct
console.log(a2) //values are present and correct
 return { a: a1, b: a2};
}

/*
  where

   array1:[
   {
    a: 1,
    b: 'skdfhkdj',
    c:[
     {
       index:0,
       code :'red'
     },
     {
       index:1,
       code :'redcwrg'
     }
    ]
   }
  ],
  
 array2:[
   {
    a: 1,
    b: 'skdfhkdj',
    c:[
     {
       index:2,
       code :'redaxac'
     },
     {
       index:3,
       code :'reddd'
     }
    ]
   }
  ]
*/

const result = filterObject(object, null,null);
console.log(result); //**gives undefined**.   

问题 当我尝试调用此函数时 const result = filterObject(object, null,null) (null,这里的 null 是数组的起始值。它们在函数的开头被分配给 [] 然后当递归发生时它们也被发送以便新数组可以更新)

当我记录它时,结果是“undefined”类型,我确信函数在return 发生

之前确实有数组中的对象

所以我哪里错了?

提前致谢

缺少一个重要的东西:您的代码没有 return 从递归调用中 return 对象。对于基本情况,它只有一个 return。您的代码不执行另一个递归情况的 return。

所以要说清楚,你需要

return filterObject(untreatedObject, a1, a2);