Generate a new entity by merging two objects containing keys that are identified by dots

I have a unique input as shown below:

{
survey.subObject1.key1: true,
survey.subObject1.key2: "OTHER",
survey.subObject2.key3: "[1,2]",
survey.subObject2.key4: false,
survey2.subObject3.key5: false,
survey2.subObject3.key6: false
}

I am looking to convert it into an object structure like this:

{
  survey: {
    subObject1 : {
      key1: true,
      key2: "OTHER"
    },
    subObject2 : {
      key3: "[1,2]",
      key4: false
    }
  },
  survey2: {
    subObject3 : {
      key5: false,
      key6: false
    }
  }
}

Currently, I am able to stringify the keys and iterate through them using a for loop, but I am struggling with recreating the object structure afterwards:

const x = {
"survey.subObject1.key1": true,
"survey.subObject1.key2": "OTHER",
"survey.subObject2.key3": "[1,2]",
"survey.subObject2.key4": false,
"survey2.subObject3.key5": false,
"survey2.subObject3.key6": false
}

for (const [key, value] of Object.entries(x)) {
      console.log(key)
      console.log(value);
}

Answer №1

While it may not be the most visually appealing code, this solution is indeed functional!

The approach involves using the reduce method on the array generated by Object.entries, then accumulating the objects with the help of the spread (...) operator.

const data = {
"survey.subObject1.key1": true,
"survey.subObject1.key2": "OTHER",
"survey.subObject2.key3": "[1,2]",
"survey.subObject2.key4": false,
"survey2.subObject3.key5": false,
"survey2.subObject3.key6": false
}

const transformedData = Object.entries(data).reduce( (accumulator, entry) => {
   const [key1, key2, key3] = entry[0].split('.');
   return {
      ...accumulator, 
      [key1]: {
         ...accumulator[key1], 
         [key2]:{
            ...(accumulator[key1]? accumulator[key1][key2] : {}), 
            [key3]: entry[1]
         }
      }
   };
}, {});

console.log(transformedData);

Answer №2

I recently came across a great solution using https://www.npmjs.com/package/dot-object for handling nested objects in JavaScript. With this package, you can achieve the following:

const data = {
"user.details.name": "John Doe",
"user.details.age": 30,
"user.preferences.darkMode": true
};

// Convert to dot notation
const convertedData = dot.object(data);

// Revert back to original structure
const revertedData = dot.dot(convertedData);

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

Avoiding server requests in Firefox by refraining from using ajax

I've implemented the following jquery code: $("#tasksViewType").selectBox().change( function (){ var userId = $('#hiddenUserId').val(); var viewTypeId = $("#tasksViewType").val(); $.post('updateViewType& ...

The failure of the Selenium script can be attributed to the presence of the AJAX

Struggling to automate an application with an AJAX loader causing issues? Getting the dreaded error message about element not being clickable when the loader is active? Frustrating, right? But fear not! I have devised a clever solution in the form of a wr ...

JavaScript compilation failure: Unhandled SyntaxError: Unforeseen token '>' in string variable within an if statement -- Snowflake

Looks like there's an issue with JavaScript compilation. The error message reads: Uncaught SyntaxError: Unexpected token '>' in HP_SEARCHCBHMESSAGES at ' if (Fac123 <> "") ' position 1.. Strange how SF is not a ...

Having difficulty with the useState hook in a material ui functional component that integrates with Firebase

Currently, I am endeavoring to create a sign-up form utilizing a Material UI functional component. Within this form, I am aiming to trigger a signup event by using the "onClick" attribute attached to the sign-up button. My approach involves passing the ema ...

Setting up JW Player with a YouTube Embed URL

Embed link Is it possible to embed a YouTube link in my JW Player without disrupting the design? I have a specific design for the JW Player frame that I need to retain while incorporating the YouTube link. I have searched extensively but haven't foun ...

How can I use jQuery to either display or hide the "#" value in a URL?

I have a question that I need help with. Let's say I have the following links: <a href="#test1"> Test </a> <a href="#test2"> Test 2 </a> When I click on Test, the URL will change to something like siteurl/#test1. However, whe ...

"Exploring the best method to utilize a for loop for updating an array of objects in

I'm looking to update a nested mongo document using a for loop with my node.js code below: //loop starts var update = { "rate":mainRate, "classifierCategories."+e+".rate":temiz[i].slice(0,2) }; classifier.update({"classifierS ...

Transforming the color of a globe from black to white with gio js

After searching for a solution to change the color of a Three.js globe, I came across a link that didn't work as expected: Change the color of a Three.js globe. My goal is to change the globe color from black to white using . I attempted to use the f ...

Import a JSON file into Parse by reading and parsing it to store in the database

I am currently facing a challenge with parsing JSON data in my Parse Cloud function. After fetching the JSON file, I need to parse the data and populate one of my classes with the results. However, I'm having trouble figuring out how to properly parse ...

To run multiple environments with react-native-dotenv in a React Native project using Typescript, only the local environment is activated

Currently, I am facing an issue while trying to initialize my React Native app with TypeScript in three different environments - development, local, and testing. When I attempt to run APP_ENV=testing expo start or APP_ENV=development expo start, it always ...

Decoding the enigma of addEventListener in Nuxt: Unveiling the "referenceError: window is not defined" issue

I am currently working on developing a hamburger menu, but I have encountered an error. The error message states: ReferenceError: window is not defined. The issue seems to be within the created section of the code. <script> export default { ...

Creating a Typescript project that compiles to UMD format, however, encountering the challenge of

I am trying to convert my index.ts file into a UMD index.js so that I can use it with a <script> tag. Here is the TypeScript configuration I am using: { "compilerOptions": { "outDir": "dist", "declaration& ...

Navigating the maze of Material UI in React with TypeScript

I have a functioning code, but I am trying to incorporate Material UI into it. However, when I replace 'input' with 'TextField', I encounter the following error: Uncaught (in promise) Error: Request failed with status code 422 at cr ...

Interfaces and Accessor Methods

Here is my code snippet: interface ICar { brand():string; brand(brand:string):void; } class Car implements ICar { private _brand: string; get brand():string { return this._brand; } set brand(brand:string) { this. ...

Console displays 'undefined' when using the post method with Node.js/Express

Below is the code for my upload.ejs page: <%- include('header' ,{ title:"Playground" }) -%> <div class="wrapper"> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="text" name="name" place ...

Is there a way to send the image's name as a parameter?

I am facing a challenge in achieving a specific task and need some guidance. My current approach involves passing the image name as a parameter to the cancelimage.php script, but it seems like I am not utilizing the variable 'image_file_name' cor ...

$filter is functioning correctly, however it is generating an error message stating: "Error: 10 $digest() iterations reached. Aborting!"

Here is an example of a JSON object that I am working with: { "conversations":[ { "_id": "55f1595d72b67ea90d008", "topic_id": 30, "topic": "First Conversation", "admin": "<a href="/cdn-cgi/l/e ...

Sending a javascript variable to an angularjs scope

Currently, I am utilizing Flask to render an HTML template and wish to transfer the variable add_html_data, which is passed via Flask's render_template, to the scope of an AngularJS controller. I have attempted the following: <body> <di ...

I am facing difficulties in adding dynamic content to my JSON file

I've encountered a challenge in appending new dynamic data to a JSON file. In my project, I receive the projectName from an input form on the /new page. My API utilizes node.js's fs module to generate a new JSON file, where I can subsequently add ...

Checking the size of an HTML numerical input field?

When creating a form that accepts numbers, there may be a specific element, such as a phone number input named phNo, that needs to be exactly 7 digits long. To achieve this validation using JavaScript, the approach is: If the length of the element is not ...