Guidance on dividing children in an object into distinct arrays

So I have an interesting challenge while working on my project. I need help figuring out how to split a Javascript Object like the one below:

{
    field1: {
        field2: {
            field3: "value 1",
            field4: "value 2"
        }
    }
}

My goal is to separate any field with multiple keys into different arrays, as shown here:

[
    {
        field1: {
            field2: {
                field3: "value 1"
            }
        }
    },
    {
        field1: {
            field2: {
                field4: "value 2"
            }
        }
    }
]

I've attempted to create recursive functions to navigate through the object structure and duplicate any object value with more than one key. Each "child" should have its own parent structure. I feel like there might be a simple solution that I'm missing, so any suggestions would be greatly appreciated!

Thank you for your help.

Answer №1

Here is a quick demo using your initial data.

However, additional test scenarios with valid results are necessary for thorough verification (as things can quickly go haywire).

const sampleInput = {
  item1: {
    item2: {
      item3: "data value 1",
      item4: "data value 2"
    }
  }
};

function flattenRecursively(data) {
  const output = [];

  for (const [key, value] of Object.entries(data)) {
    if (value && typeof value === 'object' && Object.entries(value).length) {
      for (const obj of flattenRecursively(value)) {
        output.push({ [key]: obj });
      }
    }
    else {
      output.push({ [key]: value });
    }
  }

  return output;
}

console.log(flattenRecursively(sampleInput));

Additional Examples:

function flattenRecursively(data) { const output = []; for (const [key, value] of Object.entries(data)) { if (value && typeof value === 'object' && Object.entries(value).length) { for (const obj of flattenRecursively(value)) { output.push({ [key]: obj }); } } else { output.push({ [key]: value }); } } return output; }

// Test Input 1
const inputData1 = {
  item1: {
    item2: {
      item3: "data value 1",
      item4: "data value 2"
    }
  },
  item5: {
    item6: {
      item7: "data value 3"
    },
    item8: {
      item9: "data value 4"
    }
  }
};

console.log(flattenRecursively(inputData1));

// Test Input 2
const inputData2 = {
  item1: {
    item2: {
      item3: {
        subItem1: 'subValue1',
        subItem2: 'subValue2',
      },
      item4: "data value 2"
    }
  }
};

console.log(flattenRecursively(inputData2));

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 watermark feature in HTML may not appear when printed on every page

I'm facing an issue with adding a watermark style. The watermark displays only on the first page when attempting to print in Chrome. It works perfectly in Firefox and IE. <style type="text/css"> #watermark { color: #d0d0d0; font-size: 90pt; ...

Scroll horizontally within the div before scrolling down the page

After reviewing other questions, it's important to note that the scroll I am looking for is horizontal, not vertical. My goal is to have a div on a page automatically start scrolling when it reaches the center or becomes visible, and then allow the pa ...

Laravel Eloquent model, text being cut off at maximum length

While working with Laravel, I encountered an issue when loading a database row into an Eloquent object. The problem arose from one of the columns being a longtext type containing a JSON encoded array with over 2 million characters. The original error I fac ...

Error in Mongoose validation: "Please provide a value for the 'first' field and the 'last' field."

Another user has previously posted a similar question, but I'm still struggling with my MongoDB website. I am working on a project to store names using mongoose. Here is the code for my routes and models: const router = require("express").Router(); c ...

Troubleshooting NameError when Parsing JSON with Python 2.7 and Handling NULL Results

I am attempting to extract the "b" tag from this JSON data but keep encountering a NameError. Any suggestions on how to correct this code? json_data = {"one": null, "two": {"a": "1", "b": null}, "three": "3" } if __name__=="_ ...

Using react-hook-form to easily update form data

While working on my project with react-hook-form for updating and creating details, I encountered a problem specifically in the update form. The values were not updating properly as expected. The issue seems to be within the file countryupdate.tsx. import ...

Running a service in Express.js without being dependent on incoming requests

I have a backend application built using nodeJS and express. The architecture consists of two main files, app.js for handling express configuration, controllers, and MongoDB connection, and index.js strictly for server creation. Now, I am looking to imple ...

Using ng-repeat and selectize in AngularJS to populate a multi-select drop-down with values and set selected values

In this instance, I was able to achieve pure HTML select multiple functionality by using this example (JS Bin of pure html select tag). However, instead of sticking to just the pure HTML approach, I opted to use the Selectize plugin. The confusion arose w ...

The variable fails to receive a value due to an issue with AJAX functionality

I am struggling to figure out what's causing an issue with my code. I need to store the result of an AJAX request in a variable, specifically an image URL that I want to preload. $.ajax({ type: "POST", url: 'code/submit/submi ...

Vuejs - Display multiple dates within one component

I have developed various components (such as tables, selects, etc) that all rely on the same methods to access API information. The main objective is to be able to use these components across different pages of the application in a way that allows for fle ...

``There seems to be an issue with JQuery.Ajax not properly displaying on Samsung Smart

I attempted to use JQuery.Ajax to interact with my webservice Below is the code snippet: Main.onLoad = function() { // Enable key event processing this.enableKeys(); widgetAPI.sendReadyEvent(); //$("#h2Test").html("Change On Text"); ...

Converting JSON data into Java objects

{ "city" : "THAYNE", "loc" : [ -111.011354, 42.933026 ], "pop" : 505, "state" : "WY", "_id" : "83127" } I have been given some JSON syntax and I am looking to convert it into a Java object. Initially, I crea ...

Using JavaScript to replace a radio button with the term "selected"

I am currently in the process of developing a quiz that is powered by jQuery and possibly JSON, with data being stored in a database. Everything is functioning correctly at this point, but I would like to enhance the user interface by hiding the radio butt ...

What are some other options for pushing out data instead of using window.onbeforeunload?

I have an AJAX function that interacts with my PHP script. The purpose was to delete empty MySQL entries when the user closes the page. Initially, I thought window.onbeforeunload would be ideal for this task, but it seems in the latest version of Chrome i ...

Unable to invoke the JQuery getJSON function

Struggling to implement a table with pagination using jQuery and json, as the getJSON method seems unresponsive. The JavaScript function GetPageData triggers successfully on page load. Inserting the two commented lines in the code below didn't change ...

Display visual information without requiring the parameters to be filtered beforehand in vue.js

Upon opening my page, I encountered an issue where the graphics appear blank. This is because I set up the callback for generating graphic data through params request. I wish to first fetch the general data when the page opens, and only load with params w ...

JavaScript opacity adjustments not achieving desired outcome

My attempt to make this sub menu fade in and out upon button press is not working as expected. It should fully fade in shortly after clicking 'help' and completely fade out when clicking 'back'. Is the problem with the method I'm u ...

Verifying the presence of an image via its URL may not be functional across all browsers

Hey folks, I'm working on a project that involves displaying an image along with other fields in a loop where the image source changes with each iteration. I also need to check if the image exists and set a default source if it doesn't. The code ...

According to npm, the JSON is not valid, but jsonlint.com confirms that it is valid

Here is the json file for package.json that I used npm install on (specifically for the angularfire-seed project on github): { "name": "angularfire-seed", "description": "A starter project for Angular + Firebase with AngularFire", "version": "1.0.0 ...

Leveraging a JSON file as a data repository for chart.js

I am struggling to incorporate JSON values into a bar chart. I have successfully logged the JSON data in the console, but I'm unsure how to include it in the data property for the chart. Below is the source JSON... {time: "2016-07-03T21:29:57.987Z" ...