0

I want to find the first array in an object in Javascript. However my functions cause an error:

el is undefined

el contains the object that looks like this:

data = {
   foo: {
      bar: [{object a},
            {object b},
            {object c}
           ]
   }
}


let el = data;
el = this.searchArray(el);
el.forEach(element => {
      console.log(element); 
      let siblingData = this.injectFilterParameters(element);
                        
        });
//here is unimportant code
searchArray(obj) {
    if (Array.isArray(obj)) {
        return obj;
    } else {
        Object.keys(obj).forEach(key => {
            if (Array.isArray(obj[key])) {
                return obj[key];
            } else {
                return this.searchArray(obj[key]);
            }
        })
    }
}
Zehke
  • 129
  • 1
  • 1
  • 11
  • 1
    If the error is that `el` is undefined, then that means that...`el` is undefined. The only time you assign it it `el = this.searchArray(el);` which means that `this.searchArray(el);` returns `undefined`. Not exactly surprising if `el` wasn't an array to begin with - `searchArray` only returns the input if it's an array, otherwise returns `undefined`. The `return` in the `forEach` callback doesn't return from the outer function. [What does `return` keyword mean inside `forEach` function?](https://stackoverflow.com/q/34653612) – VLAZ Jul 21 '21 at 12:55
  • It should only return when the array is found and should return the array, In each case the array is present and its always the first array – Zehke Jul 21 '21 at 13:05
  • 1
    `return` in a `forEach` doesn't return from the outer function. In fact, it basically doesn't do anything, since the `forEach` will continue. The `return` value is completely ignored. You need to use an regular loop. – VLAZ Jul 21 '21 at 13:07

1 Answers1

0
const data = {
  foo: {
    bar: [
      { object: 'a' },
      { object: 'b' },
      { object: 'c' }
    ]
  }
}

console.log(findArray(data))

function findArray(data: unknown): unknown[] | undefined {
  if (Array.isArray(data)) {
    return data
  }

  if (typeof data !== 'object') {
    return undefined
  }

  const object = data as Record<string, unknown>

  for (const key of Object.keys(object)) {
    const value = object[key]
    const valueSearchResult = findArray(value)

    if (valueSearchResult != undefined) {
      return valueSearchResult
    }
  }

  return undefined
}