Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda