spontaneously formed intricate structures

Seeking assistance with a problem regarding dynamic generation of multiple versions from an existing deep JavaScript object. This task involves a method with two parameters: first: the original object, second: either a single number or an array of numbers

For example:

let myObj = {

  brown: {
    50: '#f9f8f2',
    100: '#f3f0e6',
  },
  singleProp: '#e6b01e',
  propLvl1: {
    color: '#32a852',
    sub1: {
      color: '#44eff2',
      sub2: {
        color: '#f2448d'
      },
    },
  },
};

myFunction(myObject, [10, 30]);

The desired outcome would be:

  MY-10-brown: {
    50: '#(DYNAMICVALUE)f9f8f2',
    100: '#(DYNAMICVALUE)f3f0e6',
  },
  MY-10-singleProp: '#(DYNAMICVALUE)e6b01e',
  MY-10-propLvl1: {
    color: '#(DYNAMICVALUE)32a852',
    sub1: {
      color: '#(DYNAMICVALUE)44eff2',
      sub2: {
        color: '#(DYNAMICVALUE)f2448d'
      },
    },
  }

  MY-30-brown: {
    50: '#(DYNAMICVALUE)f9f8f2',
    100: '#(DYNAMICVALUE)f3f0e6',
  },
  MY-30-singleProp: '#(DYNAMICVALUE)e6b01e',
  MY-30-propLvl1: {
    color: '#(DYNAMICVALUE)32a852',
    sub1: {
      color: '#(DYNAMICVALUE)44eff2',
      sub2: {
        color: '#(DYNAMICVALUE)f2448d'
      },
    },
  }

Current progress made on this task includes:

export default function generateObjects(obj, numbers) {
  let newObj = {};

  for (let q = 0; q < transparentValue.length; q += 1) {

    let Obj = doTheJob(obj, transparentValue[q]);
    Object.assign(newObj, Obj);
  }
  return newObj;
}

function doTheJob(obj, number) {

  const newObj = {};
  let newKey = '';

  Object.keys(obj).forEach(function (key) {

    let trim = `${obj[key]}`.substring(1);
    let newValue = `#${anotherObject[number]}${trim}`;

    if (typeof obj[key] === 'object') {
      newKey = `MY-${number}-${key}`;
      newObj[newKey] = obj[key];
      generateNewObj(newObj[newKey], number);
      return;
    }
    if (typeof obj[key] === 'string') {
      newObj[key] = newValue;
    }
  });

  return newObj;
}

Answer №1

One way to enhance the object is by creating new properties for its top level and making copies of the existing data.

const
    duplicate = value => typeof value === 'object'
        ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, duplicate(v)]))
        : typeof value === 'string'
            ? value.replace('#', '#DYNAMICVALUE')
            : value
    createNew = (object, values, header) => Object.fromEntries(Object
        .entries(object)
        .reduce((r, [k, v]) => [...r, ...values.map(i => [[header, i, k].join('-'), duplicate(v)])], [])
    ),
    myObj = { brown: { 50: '#f9f8f2', 100: '#f3f0e6' }, singleProp: '#e6b01e', propLvl1: { color: '#32a852', sub1: { color: '#44eff2', sub2: { color: '#f2448d' } } } };

console.log(createNew(myObj, [10, 30], 'my'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

You have the ability to:

  • Initiate the creation of a fresh entity

  • Iterate through each numerical value within the array

    • While inside the iteration, examine and assign the property value to the novel object's updated property (
      "MY-"+num+"-"+prop
      ).

let myObj = {
  brown: {
    50: '#f9f8f2',
    100: '#f3f0e6',
  },
  singleProp: '#e6b01e',
  propLvl1: {
    color: '#32a852',
    sub1: {
      color: '#44eff2',
      sub2: {
        color: '#f2448d'
      },
    },
  },
};

function process(obj, numArr){
  const newObj = {};
  for(const num of numArr){
    for(const prop in obj){
      newObj['MY-'+num+'-'+prop] = obj[prop];
    }
  }
  return newObj;
}

console.log(JSON.stringify(process(myObj, [10, 30]), 0, 2))
.as-console-wrapper{max-height:100%!important;top:0}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Vue.js instance is referencing the "options" property or method during render, but it has not been defined

Working with Vue.js (and Inertia.js), I encountered an issue while trying to build a select element in my form. After compiling, the select appears empty, and the developer console in the web browser shows the following error: The property or method "opti ...

An unexpected JavaScript error has occurred in the main process: TypeError - not enough arguments provided

During my attempt to package an electron project using the electron-packager npm module, I encountered an error when running the .exe file of the packaged product. The error specifically references app/dist/packaged-app-win32-x64... and you can see the err ...

Moving the layout container towards the left: a quick guide

I am currently attempting to display the legend contents in a horizontal alignment within the layout container. The issue is that while the layout containing the legend aligns horizontally as desired, it extends beyond the screen border. I do not want the ...

Learn the steps to assign a Base64 URL to an image source

I am currently facing an issue with an image that is being used with angular-cli: <img src="" style="width: 120px; padding-top: 10px" alt="" id="dishPhoto"> The image has a Base64 url named imgUrl. My intention is to set the image source using the ...

Generate gradient background for the chart using Vue and ChartJS by accessing the canvas context within a child component

I'm facing an issue in giving my chart a gradient background color because I cannot access the canvas context since my chart is rendered within a wrapper component that I developed. Here is the desired outcome: https://i.sstatic.net/RdXEu.png The cu ...

When attempting to send coordinates to the Polyline component in React Native, an error is encountered stating that NSNumber cannot be converted to

Trying to pass coordinates from BackgroundGeolocation.getLocations() is causing an issue. Upon passing the coordinates, I encounter the following error message: JSON value '-122.02235491' of type NSNumber cannot be converted to NSDictionary I ha ...

Use regular expressions and JavaScript to enclose a series of English letters within a wrapper

I am looking to enclose a series or cluster of consecutive English characters within a <span> tag. In simpler terms, I aim to alter the appearance of English language in my writing. Therefore, I need to identify English characters and surround them ...

How can nested routes be declared in React-Router-Dom?

Currently, I am utilizing reactJs and attempting to establish nested routes. Below, you will find the routing segments of my files: main.js : ReactDOM.render( <Router> <App /> </Router>, document.getElementById(&apos ...

Loading custom places in ArcGIS from a file or database

Hey there, I was wondering about loading custom places with Arcgis similar to Google maps loading from a .xml file. I noticed that Arcgis uses examples saved in .json format, but when I tried putting the example .json on my local server it wouldn't lo ...

Having trouble using Jquery Selector to locate a div element in my Polymer project. Seems like it should be simple, but I can

Purpose: My objective is to add a new class to the div that contains a form when a specific icon is clicked. Challenge: The Jquery selector in pullupClose function is not able to identify the element. Check out the console.log result for a visual represent ...

Issues with connecting to Socket.IO in Cordova app

I'm having troubles setting up my Cordova app to establish a socket.io websocket connection. Despite following the instructions I found, it doesn't seem to connect when running in debug mode. Can anyone help me troubleshoot this issue? Server Si ...

Excluding certain images from a JavaScript Photobox animation within a div - a step-by-step guide

Currently, I am using photobox to showcase all the images in a div as part of a beautiful gallery display. However, there is one image that I do not want to be included in this gallery - a PDF icon which, when clicked, should download a PDF file. The issue ...

What is the best way to make an ajax commenting system function from a separate directory?

I am facing an issue with implementing an ajax commenting system on my website. When I place all the code from the /comment directory directly in the root, everything works fine and the commenting system functions as expected on new pages. However, when I ...

Using Handlebars: Send the position of every item to a nested statement

Is it possible to pass each index or key to the nested expression in handlebars? //Not working {{#each thumbs}} <img src="{{src}} data-large="{{../<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfa6a2aea8aabce18 ...

Tips on removing authentication token when logging out in react native

Working with the Django Rest Framework and React Native for the front-end, I am currently facing an issue where the authentication token persists even after a user logs out from the front-end. This is evident as the token still shows in the Django admin pa ...

The function Math.random when applied to arrays

I'm trying to wrap my head around how arrays and functions like Math.random() work together. When the Math.random() function generates a number between 0 and 1, how does that correspond to specific values in an array? For instance, in the code snippet ...

How can I prevent this parsing error from happening? Implementing JSON with double quotation marks

In the JSON string object, we typically have properties and their corresponding values formatted as "Property":"Value". However, if the value itself contains a double quote, such as in the example "Property": "my country is "uk"", this can result in a par ...

Leveraging python capabilities within html documents

English is not my first language, so please excuse any spelling errors. I am working on combining HTML and Python to develop a graphical user interface (GUI) that can communicate with a bus system (specifically KNX bus). Currently, I have a Raspberry Pi ...

Is it necessary to perform a specific action if the text within a div matches pre

I've been struggling to make this work properly. Even after removing the AJAX POST function, the issue persists. No alerts or any indication of what's going wrong. Check out the code on JSFiddle: HTML <div class="notification"> ...

What steps can be taken to resolve the delay in transition when clicking on "read less

I implemented a transition effect for the Read More and Read Less buttons, however, there seems to be a delay on the transition when clicking on the Read Less button. This delay was not intentionally set by me. How can I resolve this issue and also apply a ...