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

Save a PNG file using the HTML5 Canvas when the Submit button is clicked, with the help of PHP

I am looking for assistance with a signature capture form. I came across a standard template on Github that works perfectly, but I wanted to customize it further. However, my Javascript skills are still in the early stages. The current code allows you to c ...

Is the JSON returned by WCF Data Services incorrect?

Currently, I am in the process of updating a software application that previously utilized jQuery 1.3.2 to interact with a WCF Data Service (also known as ADO.NET Data Services or Astoria) to now work with the most recent version of jQuery (1.4.2). Unfortu ...

What is the best way to implement CSS in this JavaScript Fetch code in order to manipulate the text's position and font style

Hello, I am just starting out with JS. Is there a way for me to customize the position and font of text in this JS Fetch function using CSS? Any help will be greatly appreciated. let file = 'art.txt'; const handleFetch = () => { fe ...

Is there a way to generate a checkerboard dynamically with the help of jQuery?

I've made some progress so far, but I'm facing a challenge where I need to push 8 <td> elements into 8 different <tr> elements without hardcoding anything or modifying the HTML directly. Any help would be appreciated! JavaScript v ...

Authenticating the identity of the client application - the client is currently within the browser

I have a PHP backend (although it's not really important) and a Javascript client that runs in the browser. Here is how the application operates: The user accesses a URL and receives raw templates for rendering data An Ajax GET query is sent to the ...

Combine two scope arrays in AngularJS

Is there a way to merge two arrays of scope in AngularJS within my controller so that I can display them in a single table? The merging would be based on a common field present in both arrays, similar to an SQL join operation where data from both tables ...

Enhance your Vue PWA by utilizing ServiceWorker to efficiently cache remote media assets fetched from an array of URLs

In my PWA development project, I am looking to provide users with the option to download and cache all media assets used in the application. However, the default behavior of PWAs only caches assets when they are requested during app navigation. My goal is ...

Webdriverio: exploring the window object

I am experimenting with Webdriverio Testrunner using Selenium Standalone. I have encountered an issue while trying to check a global variable (window.myVar) in one of my tests. When attempting to return the window object, I am getting unexpected results i ...

Parsing JSON with PHP when dealing with an array that is not consistent

My current predicament involves receiving data from my android app in the following format: {"uid":1, "newAdd":"New York", "coupon_status":"yes", "coupon_code":"SALE50", "place_code":4, "basket":[{"name":"xyz", "vendorId":1, "total":100, "count":2}, {...} ...

Creating a Higher Order Component (HOC) for your Next.js page

Upon running the following code, I encountered an error message Error: The default export is not a React Component in page: "/" pages/index.tsx import React, { useState, useRef } from "react"; import type { NextPage } from "next&q ...

HtmlWebpackPlugin can cause issues with loading relative path files on websites that are not located in the root directory

I have set up webpack and the HtmlWebpackPlugin to automatically include bundled js and css files in an html template. new HtmlWebpackPlugin({ template: 'client/index.tpl.html', inject: 'body', filename: 'index.html' ...

Tips for successfully passing multiple properties to a function in React

<DeleteForeverIcon className={classes.deleteHwIcon} onClick={() => { deleteHomework(value.name, value.class); }} /> I'm looking to modify the function deleteHomework so that it can receive two properties instead of just one. In add ...

Vue2: when passing a function as a prop, a warning will be triggered indicating that the prop has

As a newcomer to Vue, I've been enjoying working with Single File Components. Before diving into my main project idea, I decided to experiment with some small components to get a better grasp of the concept. One such experiment involved creating a co ...

When the time comes, ReactDOM will render your element into the designated container,

What does the [,callback] parameter represent in the ReactDOM.render(element, container) method? ...

Decode JSON data from an array using the HTTParty gem in Ruby

Just diving into the world of Ruby and seeking some guidance. Currently, I am working with HTTParty to fetch data from an API. However, the response is in the form of a JSON array that is proving to be a bit challenging to parse. #<Net::HTTPOK:0x1017 ...

Enhancing table field functionality in Backbone.js

In my Backbone application, I am trying to debug the following code outline. window.TableView = Backbone.View.extend({ initialize: function() {... .. .. ... }); }, selectRow: function() { ... ... .. }, render: function() { // ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

Acquiring the safe area of the iPhone X through JavaScript

The CSS properties safe-area-inset-left, safe-area-inset-right, safe-area-inset-top, and safe-area-inset-bottom are available, but is there a way to retrieve these values using JavaScript? ...

What is the best way to assign attributes to multiple HTML elements using an array?

Seeking assistance to hide various sections in my HTML file upon button click, with the exception of one specific section. Encountered an error message: Uncaught TypeError: arr[i].setAttribute is not a function Here's a snippet of my code: const hide ...

"Step-by-step guide on assigning a class to a Component that has been

When attempting to pass a component as a prop of another component, it functions correctly. However, when I try to pass a Component and manage its CSS classes within the children, I find myself stuck. I am envisioning something like this: import Navbar fr ...