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

110
Visualizações
JavaScript : Apply a function / replacement to each element in Object/JSON, regardless of whether its nested object or array

Problem Description


Assume I have a nested object/JSON (should not matter how complex, how nested it is) - maybe a long tree with a lot of children.

I would like to apply a function or replace each key-value pair by a new predefined key value pair. If the value of a certain key is an object, I want to apply it on each of its children, not on the object itself. Same counts for arrays. It should be always applied to the children, regardles of whether its an array or an object.

(That makes it difficult in my opinion, thats why I dont find a solution)

Example


Example data object:

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"
        },
        ]
    };

No assume, that I want to apply a function to it that replaces each key-value pair where the value is a simple element, not an array or object itself (!!) Thus, the manipulated object would look like:

Operation on object : replace each key value pair with object

{[key]: [value], 'style' : {backGroundColor : 'red'}

{
  "desk": {
    {"drawer": "stapler", 'style' : {backgroundColor :'red'}}
  },
  "cabinet": {
    "top drawer": { 
       {"folder1": "a file", 'style' : {backgroundColor :'red'}},
       {"folder2": "secrets", 'style' : {backgroundColor :'red'}}"
    },
     {"bottom drawer": "soda", 'style' : {backgroundColor :'red'}}
  },
  "item" : [
    {
      "hello" : {
         {"world": "isHere", 'style' : {backgroundColor :'red'}}"
      },
      {"test": "1", 'style' : {backgroundColor :'red'}}"
    },
        {
      "hello" : {
         {"world": "isHere2", 'style' : {backgroundColor :'red'}}
      },
       {"test": "2", 'style' : {backgroundColor :'red'}}
    },
    ]
};
about 4 years ago · Juan Pablo Isaza
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