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

jQuery automatic slider for seamless transitions

I am in need of assistance with the coding for a website I'm currently constructing at www.diveintodesign.co.uk/ChrisMcCrone/index.html The coding being used is sourced from http://jquery.malsup.com/cycle/ The central large image functions as a slid ...

A guide on implementing Google reCAPTCHA in a Nuxt.js website

Trying to implement the recaptcha-module from nuxt-community in my Nuxt project but struggling with verifying if the user has passed the check. The documentation and example provided are not clear enough for me (https://github.com/nuxt-community/recaptch ...

Issues in the d3.js chart

I'm facing an issue with some incorrect lines appearing in my d3.js chart. Strangely, the problem seems to disappear when I switch tabs on Chrome and return to the chart's tab. It's puzzling to figure out the root cause of this issue, so I ...

AngularJS single-page application with model-view-controller style designs

Hey there, I'm relatively new to AngularJS and currently on a steep learning curve. I've been working on developing an AngularJS SPA and have grasped the basics. I'm using ngRoute for routing and have put together a basic application framew ...

Dynamic popup in RShiny interface with the ability to be moved around

I am currently working on a dashboard project and I am looking to implement a dynamic popup feature that can be moved around. I have been able to create a pop-up, but it remains static. I would like the flexibility for users to drag and position the popup ...

TypeScript is unable to recognize files with the extension *.vue

Can someone assist me with an issue I'm facing in Vue where it's not detecting my Single File Components? Error message: ERROR in ./src/App.vue (./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/Ap ...

Having issues with the Carousel feature in Bootstrap 5.3.1 while using Angular version 15

I'm currently in the process of setting up a carousel on my homepage. It seems like everything is in place, but there's something missing. The initial image, text, and arrows all display properly, but they are non-functional. I have correctly imp ...

Attempting to save MongoDB data into a variable for integration with Handlebars.js

Having an issue with storing MongoDB data in a variable to display in HTML using hbs. The specific error message is TypeError: Cannot read property 'collection' of undefined. Here's the code snippet I have written: const express = require(& ...

Challenges with ExpressJS 4 middleware

Trying to grasp the concept of middleware in ExpressJS 4 has been quite a challenge for me. As far as I understand, middleware are applied based on the order they are declared and can be "bound" at different levels. My current focus is on binding a middl ...

Unraveling nested JSON Response in Struts 2 jQuery <sj:select> tag - A step-by-step guide

Currently, I am developing a web application that utilizes Struts2 and its jQuery Plugin. The <sj:select> tag in my code below works perfectly when the JSON response is not nested: <s:url id="remoteurl" namespace="/XYZ" action= ...

Tips for changing the dimensions of the canvas?

I'm struggling to display a photo captured from the webcam. The sizes are not matching up, and I can't pinpoint where the size is defined in the code. https://i.stack.imgur.com/Is921.png The camera view is on the left, while the photo should be ...

Is it possible for me to move props object deconstruction into a separate module?

Here is my scenario: I have two React components that share 90% of the same props data, but display different HTML structures. I would like to avoid duplicating variable declarations in both component files. Is there a way to extract the common props des ...

Javascript: Troubleshooting Unexpected Variable Behavior in HTML Code

My issue is as follows: I am attempting to retrieve text from a JSON file in my HTML. In the header of my HTML, I have linked a tag with the following code: var language = ""; var langDoc = null; //Function to change the value function setLang() { v ...

In my Node.js/Express.js application, I have a directory that holds various images. Whenever I attempt to view these images via their URL, I encounter a 404 error message

In my Node.js/Express js project, I have the following folder structure: root ----bin ----controllers ----middleware ----models ----node_modules ----public --------images ------------test.png ----routes ----views I am currently trying to determine the cor ...

Having trouble clicking or interacting with JavaScript using Selenium and Python

Issue: Unable to interact with elements on a specific webpage after opening a new tab. Using WebDriver Chrome. I can successfully navigate the initial webpage until I click a link that opens a new tab, at which point I am unable to perform any actions. ...

Need for input

I am working on organizing my routes in a separate file from app.js. The login route requires access to a Firebase instance. routes/auth.js var express = require('express'); var router = express.Router(); module.exports = function(firebase) { ...

Encountered an undefined error while trying to read promises

I'm attempting to receive a response from a function in order to trigger another function, but I am not receiving the expected response. I encountered the following error message: "TypeError: Cannot read property 'then' of undefined." In my ...

Are there any JavaScript libraries available that can mimic SQLite using localStorage?

My current application makes use of SQLite for storage, but I am looking to switch it up to make it compatible with Firefox and other browsers. I've been considering localStorage as an option. However, I've noticed that localStorage lacks some o ...

What could be causing React to throw an invalid hook error when using useRoutes?

I encountered an error while attempting to add a new route to my project. import React from "react"; import News from "./NewsComponents/News"; import Photos from "./PhotosComponents/Photos"; import Contact from "./Contact"; import Home from "./Home"; ...

Having trouble with my findIndex function in Node.js while working with a mongo DB database

I am having difficulty finding the index of a specific product in a MongoDB database. const cart = await this.model.findOne({ user: { $eq: user } }); if (cart) { const itemFound = cart.products.findIndex( (item) => item._id === ...