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

361
Visualizações
JavaScript: Parameter not passed to Array.forEach inside of the function => undefined?

const data = {
  "desk": {
    "drawer": "stapler"
  },
  "cabinet": {
    "top drawer": { 
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottom drawer": "soda"
  },
  "item" : [
    {
      "hello" : {
        "world" : "isHere"
      },
      "test" : "1"
    },
        {
      "hello" : {
        "world" : "isHere2"
      },
      "test" : "2"
    },
    ]
};

const iterate = (obj) => {
  
    Object.keys(obj).forEach(key => {

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
    } else{
        let value = obj[key];
        let newObj = {[key]: value, 'style' : {backGroundColor : 'red'}};
        delete obj[key];
        Object.assign(obj, newObj);
    }
    })
}

iterate(data);
console.log(data)

I have wrote a recursive function that should replace each key-value pair (not property!) with a object that i specify in the parameter.

However, if I use a array.forEach loop inside the function, the passed obj is undefined.

What am I missing?

Example


const iterate = (obj, newObj) => {

    Object.keys(obj).forEach(key => {

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
    } else{
        delete obj[key];
        Object.assign(obj, newObj);
    }
    })
}

However, if I define the object within the forEach, it works perfectly ....

const iterate = (obj) => {

    Object.keys(obj).forEach(key => {

    if (typeof obj[key] === 'object') {
            iterate(obj[key])
    } else{
        let value = obj[key];
        
        // SEE HERE
        let newObj = {[key]: value, 'style' : {backGroundColor : 'red'}};

        delete obj[key];
        Object.assign(obj, newObj);
    }
    })
}

Why does the Object.keys(obj).forEach not see the passed parameter in the first version? And what is the solution?

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

0

You need to pass newObj whenever you call iterate inside the Array.forEach() - iterate(obj[key], newObj):

const data = {"desk":{"drawer":"stapler"},"cabinet":{"top drawer":{"folder1":"a file","folder2":"secrets"},"bottom drawer":"soda"},"item":[{"hello":{"world":"isHere"},"test":"1"},{"hello":{"world":"isHere2"},"test":"2"}]};

const iterate = (obj, newObj) => {
  Object.keys(obj).forEach(key => {
    if (typeof obj[key] === 'object') {
      iterate(obj[key], newObj)
    } else {
      // delete obj[key]; // remove for example purposes
      Object.assign(obj, newObj);
    }
  })
}

const newObj = {
  'style': {
    backGroundColor: 'red'
  }
};

iterate(data, newObj);
console.log(data)

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