Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!