Creating JSON from an array by grouping common values.Would you like another rewrite?

Hey there, I'm facing a small issue with arrays similar to the ones below:

const arrays = {
    1: [c, u, g],
    2: [c, u],
    3: [c, u ,f],
    4: [c, g],
    5: [m, c, g],
    6: [u, m]
}

Each array contains unique values. Now, I'm looking to transform them into an object structure like this:

const object = {
  c: {
    u: {
      g: {
        ends: 1
      },
      f: {
        ends: 3
      }
      ends: 2
    },
    g: {
      m: {
        ends: 5
      }
      ends: 4
    }
  },
  u: {
    m: {
      ends: 6
    }
  }
}

Is it achievable? If so, any hints, code snippets, or advice would be greatly appreciated as I'm currently stuck on this problem.

Answer №1

To iterate through the object entries and use the reduce method on the value arrays to create nested objects in each loop. The final result is a nested object with an additional ends property.

If you prefer unsorted nested paths, you can exclude the sort step.

const input = {
  1: ["c", "u", "g"],
  2: ["c", "u"],
  3: ["c", "u", "f"],
  4: ["c", "g"],
  5: ["m", "c", "g"],
  6: ["u", "m"]
}

const output = {};

for (const [n, paths] of Object.entries(input)) {
  paths
    .sort()
    .reduce((acc, path) => (acc[path] = acc[path] || {}), output)
    .ends = +n
}

console.log(output)

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

What causes Next.JS to automatically strip out CSS during the production build process?

Encountering unpredictability in CSS loading while deploying my Next.JS site. Everything appears fine locally, but once deployed, the CSS rules seem to vanish entirely. The element has the attached class, yet the corresponding styling rules are nowhere to ...

Is it possible to get intellisense for Javascript in Visual Studio Code even without using typings?

Is it possible to have intellisense support in Visual Studio Code for a 3rd party library installed via npm, even if there is no typings file available? I have noticed this feature working in IntelliJ/Webstorm, so I believe it might be feasible. However, ...

Is it possible to utilize waxjs for retrieving data on NFTs within the Wax Cloud Wallet?

I am currently in the process of incorporating the Wax Cloud Wallet into my React/NextJS application. To achieve this, I am utilizing waxjs and referencing the documentation available here. At present, users can log into their accounts and the applicatio ...

Exploiting the Benefits of Multiple BaseURLs with Require.js

My project has a structure that resembles the following: /path/to/project /apps /app1 /js /modules /bar.js /etc.. /app1.js /app1.build.js ...

When utilizing the map function to render an array of objects, React encounters an error

My React application is throwing an error when using the map function. Interestingly, the code works fine in a sandbox environment. Error: ENOSPC: System limit for number of file watchers reached, watch. After creating a new React project, the error dis ...

Adding content in real-time at the current cursor position within a Contenteditable element using Angular

I have a contenteditable div where I am facing an issue with pasting text. Whenever I try to paste some text into the div, it always gets pasted at the end. I am using ViewChild to access the reference of the contenteditable div and utilizing innerText to ...

Challenges arise when adjusting frame size for mobile and desktop devices

I am trying to achieve an auto-resize feature for my frame's height when the screen width is smaller than a certain value. I want it to behave like Sketchfab, as demonstrated in this video: http://www.youtube.com/watch?v=_y5ckVFGHKU&feature=youtu. ...

Using jQuery, you can easily insert a <span> tag around selected text and then save this modification permanently in a local HTML file

I have compiled notes in an HTML file stored on my local computer, with the intention of keeping it solely for personal use. For instance, I have a snippet like this: <p> this is an example text</p> My goal is to highlight the word "example" ...

Ways to specify the default value for a component

A sample of my custom component code (Amount.tsx) is shown below: const Price = ({ price, prevPrice }) => { return ( <div className="product-amount"> <div className="price"> {prevPrice ? (<del class ...

Having difficulties executing AJAX requests on Codepen.io

My CodePen project that I created 6 months ago is no longer functioning properly. The project includes an Ajax call to retrieve data using jQuery.ajax(). When attempting to load the content from CodePen via https, even though the ajax request is through h ...

Retrieve a specific line of code from a snippet of JavaScript

I am looking to extract a specific line of code from a script that I am receiving via ajax... The line in question is new Date(2010, 10 - 1, 31, 23, 59, 59) found within the following snippet: jQuery(function () { jQuery('#dealCountdown').count ...

Error: The JQUERY autocomplete is throwing an uncaught type error because it cannot read the property 'length' of an undefined value

These scripts are being utilized at this source I have implemented jQuery Autocomplete to search for users in my database. Below is the controller code returning Json: public function searchusers1() { if ($_GET) { $query = $this -> input ...

Adjusting the input in a Textfield within React using Material UI

const [formData, setFormData] = useState({}); useEffect(() => { fetch("/formdata") .then((res) => res.json()) .then((data) => setFormData(data)); }, []); console.log("Form Data", formData); //Sorting by order let attr; ...

adjusting array based on screen size fluctuations

Imagine having two arrays of images named landscape_images[] and portrait_images[]. One is for the landscape view and the other for the portrait view. When the screen width is in landscape mode, the wide resolution images will be displayed on the body. C ...

What makes Angular date pickers sluggish?

Have you ever noticed that Angular JS date pickers consume a lot of CPU? When multiple date pickers are present on a page, they can noticeably reduce the site's speed. Is there a way to minimize this issue? Take for example the official Angular for ...

Navigate between pictures using hover in jQuery

I am working on creating a feature where images cycle through individually every 2 seconds, but switch to the right image when its associated link is hovered. So far, I have managed to make the images show up on hover, but I am struggling with getting them ...

Choose checkboxes based on the checkboxes that were previously selected

My goal is to have a checkbox automatically selected based on the previously selected checkbox. For example, if I select the first checkbox (which has a specific class), then only the checkbox with the same class as the first one should be selected using j ...

I encountered difficulty in assigning a JSON response to a variable, both with and without using JSON.parse()

I'm in the process of creating a website that, among other things (and crucially for this particular issue), stores your current location data in a variable by fetching it from the ipinfo API (https://ipinfo.io/json) After encountering the problem of ...

Working with nested objects in a React functional component's state using TypeScript

In my React functional component state, I have a nested object that I can only access the first level of if I use the any type. export default function Detail() { const [user, setUser] = useState<any>({}); const { id } = useParams(); us ...

Use jQuery to smoothly scroll a div

I created a container using a <div> element which is divided into 3 inner divs. The first two inner divs are meant to serve as previous and next buttons, with ids of prev and next respectively. At the bottom, there are 3 more inner divs, each with un ...