Creating a new object through manipulation of existing objects

In my attempt to transform an existing object into a new object structure, I am facing some challenges.

Here is the current data set:

const jsonStructure = {
    "a11/a22/animations": "snimations",
    "a11/a22/colours": "sl/colours",
    "a11/a22/fonts": "sbal/fonts",
    "a11/a22/visibility": "sisibility",
    "a11/b22/logo": "sages/logo",
    "a11/c22/define": "sst/define",
    "a11/c22/ordered": "st/ordered",
    "a11/c22/unordered": "sunordered",
    "a11/d22/foot": "smeta/foot",
    "a11/d22/head": "smeta/head",
    "a11/e22/blockquote": "slockquote",
    "a11/e22/headings": "s/headings",
    "a11/e22/hr": "ss/e/hr",
    "a11/e22/inline-elements": "s-elements",
    "a11/e22/paragraph": "sparagraph",
    "a11/e22/preformatted": "sformatted",
    "a11/e22/time": "stext/time",
    "b11/f22/menu": "smenu/menu",
    "b11/g22/product-item": "sduct-item",
    "b11/h22/search": "sch/search",
    "b11/i22/sub-menu": "s/sub-menu",
    "c11/j22/footer": "ser/footer",
    "c11/j22/title": "ster/title",
    "c11/k22/header": "ser/header"
};

The desired data structure should look like this:

{
  "a11": {
    "a22": {
      "animations": {
        "value": "snimations"
      },
      "colours": {
        "value": "sl/colours"
      }
    },
    "b22": {
      "logo":{
        "value": "sbal/fonts"
      }
    }
    "c22": {
      "define":{
        "value": "sst/define"
      },
      "ordered":{
        "value": "st/ordered"
      }
    }
  },
  "b11": {
    "f22": {
      "menu": {
        "value": "smenu/menu"
      }
    },
  }
}

I am struggling with structuring the code properly and creating the object in the desired format. My attempts so far have not been successful.

const structure = {
    a: {},
    b: {},
    c: {}
};

let a11 = [];
let b11 = [];
let c11 = [];

for (var hbp in jsonStructure) {
    if (hbp.includes("a11")) {

    }
    if (hbp.includes("b11")) {

    }
    if (hbp.includes("c11")) {

    }
}

Answer №1

One approach is to create a function that can split the path and generate new objects based on it.

var input = { "a11/a22/animations": "snimations", "a11/a22/colours": "sl/colours", "a11/a22/fonts": "sbal/fonts", "a11/a22/visibility": "sisibility", "a11/b22/logo": "sages/logo", "a11/c22/define": "sst/define", "a11/c22/ordered": "st/ordered", "a11/c22/unordered": "sunordered", "a11/d22/foot": "smeta/foot", "a11/d22/head": "smeta/head", "a11/e22/blockquote": "slockquote", "a11/e22/headings": "s/headings", "a11/e22/hr": "ss/e/hr", "a11/e22/inline-elements": "s-elements", "a11/e22/paragraph": "sparagraph", "a11/e22/preformatted": "sformatted", "a11/e22/time": "stext/time", "b11/f22/menu": "smenu/menu", "b11/g22/product-item": "sduct-item", "b11/h22/search": "sch/search", "b11/i22/sub-menu": "s/sub-menu", "c11/j22/footer": "ser/footer", "c11/j22/title": "ster/title", "c11/k22/header": "ser/header" },
    output = {};

Object
    .entries(input)
    .forEach(([k, v]) =>
        k.split('/').reduce((o, k) => o[k] = o[k] || {}, output).value = v);

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To create a nested object with all paths in JSON structure, you can utilize the .split method like this:


 const newObj = {};

 for(const [prop, val] of Object.entries(jsonObj)) {
   let temp = newObj;
   for(const keys of prop.split("/"))
     temp = (temp[keys] || (temp[keys] = {}));
   temp.value = val;
}

Answer №3

Loop through the entries of an input object, utilizing a nested reduce function to find (and generate if needed) the nested object in the accumulator, and then assign its value to the value property:

const jsonStructure={"a11/a22/animations":"snimations","a11/a22/colours":"sl/colours","a11/a22/fonts":"sbal/fonts","a11/a22/visibility":"sisibility","a11/b22/logo":"sages/logo","a11/c22/define":"sst/define","a11/c22/ordered":"st/ordered","a11/c22/unordered":"sunordered","a11/d22/foot":"smeta/foot","a11/d22/head":"smeta/head","a11/e22/blockquote":"slockquote","a11/e22/headings":"s/headings","a11/e22/hr":"ss/e/hr","a11/e22/inline-elements":"s-elements","a11/e22/paragraph":"sparagraph","a11/e22/preformatted":"sformatted","a11/e22/time":"stext/time","b11/f22/menu":"smenu/menu","b11/g22/product-item":"sduct-item","b11/h22/search":"sch/search","b11/i22/sub-menu":"s/sub-menu","c11/j22/footer":"ser/footer","c11/j22/title":"ster/title","c11/k22/header":"ser/header"}

const output = Object.entries(jsonStructure).reduce((a, [keysStr, val]) => {
  const keys = keysStr.split('/');
  const finalObj = keys.reduce((nestedObj, key) => {
    if (!nestedObj[key]) nestedObj[key] = {};
    return nestedObj[key];
  }, a);
  finalObj.value = val;
  return a;
}, {});
console.log(output);

Answer №4

The responses provided above offer effective solutions that do not require the use of an external package. However, it is important to mention the presence of the flat package on npm, which can be utilized for unflattening an object. To implement this, you will need to define the delimiter as '/' in your specific scenario:

var unflatten = require('flat').unflatten

unflatten(yourObject, { delimiter: '/' })

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

Experiencing an Issue with NGINX Loading Vue 3 Vite SPA as a Blank White Page

I currently have the following NGINX configuration set up: events { worker_connections 1024; } http { server { listen 80; server_name localhost; location / { root C:/test; index index.html; ...

What is the best way to retrieve text from the p tag and input it into the text field?

Looking to resolve a situation where two identical IDs exist and need to implement some JQuery. The objective is for the input value to automatically update itself based on changes in the text of the p tag. $(document).ready(function(){ ...

The issue I am facing is that the map function is not functioning correctly when I click

I am currently working on a project in ReactJs that includes a sidebar with dropdown menu functionality. Desired Outcome When I click on an option in the sidebar that has a submenu, it should display that submenu and close upon another click. Curr ...

Transform JSON-formatted NSURLRequest into a String in Swift

My process involves sending a JSON structured string via NSURLRequest, removing the urlscheme prefix, converting it to JSON, and then manipulating it as needed. urlscheme://{"Type":"photo","Name":"Photo13"} To convert NSURLRequest to a string, I used the ...

What is the most effective way to transfer a variable between two javascript files?

I am currently working on customizing the code from a github repository found at Github repo for integration with Google App Engine. However, I have encountered an issue when trying to pass a variable from /app.js to /books/crud.js. Although I have success ...

Verify whether the element within an iFrame contains any content

After conducting extensive research, I have been unable to find a satisfactory answer to my question. Therefore, I am reaching out to see if anyone has the knowledge I seek. The Goal: I aim to check the contents within an iFrame and determine whether it ...

Each styled component will yield the respective type definitions using (@types/styled-components)

Encountering a strange problem with styled-components in VSCode. Every component from styled-components is returning 'any'. I had it working previously, but unsure when it stopped and I can't spot the issue causing all components to return ...

What are the steps to incorporate @svgr/webpack into turbopack within a next.js project?

I'm encountering an issue with turbopack and @svgr/webpack in my project. According to the documentation, they should work together but it's not cooperating. When I run the project without using --turbo (turbopack), everything functions as expec ...

What is the best way to update the array in this situation?

I have a SQL query that looks like this: SELECT test_user_user_id FROM OCN.tests_users WHERE test_user_test_id = 99 $this->mDb->Query( $sql ); $students_data = $this->mDb->FetchArray(); The array I am receiving is as follows: Array ( [0] ...

Extracting data from a nested JSON array within an AngularJS template

Here is some JSON data: { "tracks": [ { "album": { "released": "2013", "href": "spotify:album:3qGeRY1wt4rrLIt1YuSwHR", "name": "The Marshall Mathers LP2 (Deluxe)", "availability": { ...

Customizing CoreUI column names in Vue

I am working with an array of item objects for a table. For example: [{ name: 'Sam', age: 24 }] Instead of using the default column names like age, I want to set custom field names. For instance, I want to display the column as Id instead of age ...

What could be causing the jQuery effect to not function properly?

After completing a course on Codecademy, I successfully ran the code. However, I prefer to copy and paste the code into my own jquery folder for future reference and practice. The objective of this project was to make the element 'krypton' bounc ...

Choose an option from a dropdown menu using JavaScript

Currently, I am working on a project that involves using javascrypt in conjunction with selenium. While attempting to search for and select an item from a list, I have encountered difficulties in selecting the element even after successfully locating it. I ...

Comparing React-Highcharts to regular Highcharts

Despite my efforts to find information on this topic through search engines, I have come up empty. So, I am turning to you with my question. Can someone explain the distinction between these two NPM packages: https://www.npmjs.com/package/highcharts htt ...

What is the best way to extract the body content from a Markdown file that includes Frontmatter

How can I retrieve the content of the body from my markdown file using front matter? Currently, it is displaying as undefined. What steps should I take to fix this issue? {latest.map(({ url, frontmatter }) => ( <PostCard url={url} content={frontmat ...

Unable to retrieve the chosen option from the datalist

I am encountering an issue with a datalist where I can't seem to retrieve the value that is currently selected when a button is clicked. Despite following recommendations from various posts on Stack Overflow, my code still returns undefined. Interesti ...

How to conceal duplicate items in Angular2

In my Angular 2/4 application, I am fetching data from a web API (JSON) and displaying it in a table. In AngularJS, I use the following code: <tbody ng-repeat="data in ProductData | filter:search | isAreaGroup:selectedArea"> <tr style="backgro ...

Exploring the Integration of jQuery AJAX in a Contact Form

I would like to incorporate AJAX functionality into a contact form. Here is the current code I have... $("#contact_form").validate({ meta: "validate", submitHandler: function (form) { $('#contact_form').hide(); ...

A dynamic image carousel featuring multiple images can be enhanced with fluid movement upon a flick of

I am trying to enhance this image slider in HTML and CSS to achieve the following objectives: 1. Eliminate the scroll bar 2. Implement swipe functionality with mouse flick (should work on mobile devices as well) 3. Make the images clickable .slider{ ove ...

AngularJS: Enhancing User Experience by Preserving View State and Setup through Routes

Is it possible in a single page application to switch back and forth between AngularJS routes while maintaining the same state? Traditionally, this would involve binding data in a parent scope. However, for views with extensive graphical elements, this me ...