Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
Typescript .forEach and for in behavior

I made a Typescript playground to show you the code and the output. I don't understand why I don't have the same result in my code when I'm using .forEach and for in loop.

I made 2 functions to trim all body parameters. The first function use .forEach() and the 2nd use for in.

Here is the functions:

function trimWithForEach(obj: any): any {
    if (obj !== null && typeof obj === 'object') {
        Object.keys(obj).forEach(function (prop) {
            // if the property is an object trim it
            if (typeof obj[prop] === 'object') {
                return trimWithForEach(obj[prop]);
            }

            // if it's a string remove begin and end whitespaces
            if (typeof obj[prop] === 'string') {
                obj[prop] = obj[prop].trim();
            }
        });
    }
}

function trimWithForIn(obj: any): any {
    if (obj !== null && typeof obj === 'object') {
        for (var prop in obj) {
            // if the property is an object trim it
            if (typeof obj[prop] === 'object') {
                return trimWithForIn(obj[prop]);
            }

            // if it's a string remove begin and end whitespaces
            if (typeof obj[prop] === 'string') {
                obj[prop] = obj[prop].trim();
            }
        }
    }
}

With the forEach() I have the good result that I want, it will trim all my body. But with for in I have a problem because only the first object conditon is triggered to make my recursive call and if I have other object types they are ignored. The recursive call works only once in all my body object in the for in loop and I don't know why.

Can you help me to understand ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In for..in loop the return is returning you out of function at the very first time it encounters the condition to be true. That's why the later items never get processed.

I am not quite sure what you are trying to do here but there is a basic difference between the way 'forEach' and 'for...in' works with regards to 'return'.

In for...in return returns the value out of function, but in forEach the return doesn't work.

Look at the following simple example for more clarity

var testfn = function() {
  let a = [1,2,3]
  let b =  a.forEach(el => {
    if ( el == 2 )
      return el
  })
  console.log("Came here!")
  console.log({b})
}

var testfn1 = function() {
  let a = [1,2,3]
  for ( let i in a ){
    if ( a[i] == 2 )
      return a[i]
  }
  console.log("Came here!")
  console.log({a})
}
testfn()
testfn1()
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda