Simple steps for transforming an array into a JavaScript object

Here is an array resembling a JSON structure with n elements:

const mainData = [
  {
    phrase: "Phrase 1",
    categorynumber: 1,
    optionnumber: 1,
  },
  {
    phrase: "Phrase 2",
    categorynumber: 1,
    optionnumber: 2,
  },
  {
    phrase: "Phrase 3",
    categorynumber: 2,
    optionnumber: 1,
  },
  {
    phrase: "Phrase 4",
    categorynumber: 3,
    optionnumber: 1,
  },
  {
    phrase: "Phrase 5",
    categorynumber: 3,
    optionnumber: 1,
  },
  {
    phrase: "Phrase 6",
    categorynumber: 3,
    optionnumber: 2,
  },
];

The goal is to transform this into a nested Object structured as follows:

jsObject = {
  1: {
    1: ["Phrase 1"],
    2: ["Phrase 2"],
  },
  2: {
    1: ["Phrase 3"],
  },
  3: {
    1: ["Phrase 4", "Phrase 5"],
    2: ["Phrase 6"],
  },
};

The data should be organized based on the categorynumber and then by optionnumber. (Pay attention to the format of "Phrase 4" and "Phrase 5".)

Answer №1

Utilize the reduce method to condense the dataset by utilizing the categorynumber as the primary key and the optionnumber as the secondary key. When adding new options to an existing category, use spreading (...) for the new option and enclose it within an array.

If you want to add extra phrases, make sure to retrieve the existing array and spread the new value accordingly.

const mainData = [
  { phrase: "Phrase 1", categorynumber: 1, optionnumber: 1, },
  { phrase: "Phrase 2", categorynumber: 1, optionnumber: 2, },
  { phrase: "Phrase 3", categorynumber: 2, optionnumber: 1, },
  { phrase: "Phrase 4", categorynumber: 3, optionnumber: 1, },
  { phrase: "Phrase 5", categorynumber: 3, optionnumber: 1, },
  { phrase: "Phrase 6", categorynumber: 3, optionnumber: 2, },
];

const jsObject = mainData.reduce((acc, { phrase, categorynumber, optionnumber }) => ({
  ...acc,
  [categorynumber]: {
    ...(acc[categorynumber] ?? {}),
    [optionnumber]: [...(acc[categorynumber]?.[optionnumber] ?? []), phrase]
  }
}), {});

console.log(jsObject);
.as-console-wrapper { top: 0; max-height: 100% !important; }
<!--

jsObject = {
  1: {
    1: ["Phrase 1"],
    2: ["Phrase 2"]
  },
  2: {
    1: ["Phrase 3"]
  },
  3: {
    1: ["Phrase 4", "Phrase 5"],
    2: ["Phrase 6"]
  }
}

-->

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

Arranging asynchronous functions using async/await in Node.js/JavaScript

When it comes to organizing my code in js/nodejs, I frequently rely on this pattern. (async function(){ let resultOne = await functionOne(); let resultTwo = await functionTwo(); return { resultOne: resultOne, resultTwo: resul ...

Slick.js integrated with 3D flip is automatically flipping after the initial rotation

I'm encountering an issue with my CSS3 carousel and 3D flipping. Whenever I navigate through the carousel and flip to the next slide, the first slide seems to automatically flip/flop after completing the rotation. You can see a visual demonstration o ...

Tips for preserving images while browsing a website built with Angular single-page application

Utilizing Angular's router for component navigation has been beneficial, but I am facing an issue with component reloads when going back. To address the problem of content reloading from the server, I have implemented a solution where the content arra ...

Switch out the content within a div upon selection

I'm currently working on a palette board project and facing some challenges when switching to a different theme. The initial page is set to have a Warm color palette, but I intend to alter this once the user clicks on the All theme option. Users wil ...

What is the best way to aggregate totals by date in Ruby when working with an array of hashes?

I'm trying to consolidate an array of arrays that represent the number of orders by week. How can I merge these arrays to calculate the total orders for each week? [ [ {:week_beginning=>Mon, 13 Feb 2017, :orders_total=>"1.00"}, {:wee ...

Creating sparse fieldset URL query parameters using JavaScript

Is there a way to send type-related parameters in a sparse fieldset format? I need help constructing the URL below: const page = { limit: 0, offset:10, type: { name: 's', age:'n' } } I attempted to convert the above ...

What is the best way to capture data sent by Express within a functional component?

const Header = (props) => { const [ serverData, setServerData ] = useState({}); useEffect(() => { fetch('http://localhost:4001/api') .then(res => res.json()) .then((data) => { setServerData(data); ...

Ways to create collapsible navigation bars in your website

As someone exploring client-side development, I may be misusing the term "collapsible" in my title. What I aim to accomplish in my web application is allowing users to collapse header bars into small chevrons and expand them back when necessary. I am on t ...

What purpose does the by.js locator serve in Protractor/WebDriverJS?

Recently, I've come across a new feature in the Protractor documentation - the by.js(): This feature allows you to locate elements by evaluating a JavaScript expression, which can be either a function or a string. While I understand how this locat ...

Using AJAX to dynamically render asynchronous requests on the DOM

As I work with a for loop to iterate through a JSON object and display results upon clicking a button on the webpage, I have encountered an issue. Whenever I click the button again, instead of displaying the next five entries in the list, it reloads the sa ...

Encountered StackOverflowError while attempting to transform criteria list output into json format

I encountered an issue while converting Hibernate criteria list results into JSON for my application. Initially, I received the error message Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter To ...

Remove HTML tags from a table cell containing a combination of radio buttons and labels

Javascript Function: My JavaScript function posted below is designed to iterate through the column indexes specified in the 2nd parameter and also iterate through the element ids provided in the 3rd parameter. It will then populate the textbox, radiobutto ...

How can I use JavaScript to create a drop-down menu that only appears after selecting the previous one?

<div class="row"> <div class="col-md-4"> <label for="selectCustomers">Customer Select</label> <select class="form-control pointer" name="tableCustomers" id=" ...

A simple guide to fetching JSON data and storing it in a variable, then parsing it and displaying it

I am looking to retrieve JSON data from the Yahoo Finance API, store it in a JavaScript variable, extract specific information such as "name" and "price", and then display it in an HTML table. The JSON data can be accessed via the following link: Current ...

Converting a custom object with JodaTime attributes into JSON serialization

Upon completing an additional task that involves creating and storing an object in an ArrayList within a Singleton, I encountered an error when transitioning back to the initial Activity from the creation process. Logcat: 10-09 15:00:48.125: E/AndroidRun ...

Update my function to be asynchronous by changing async: false to async: true using JQuery and Ajax

I've created a function in a JavaScript class that accesses a PHP file to retrieve information from a database. Although this function works well, I attempted to set the property async: true, and it caused the function to stop working. (I received th ...

Import several image files using AngularJS

I recently came across a helpful tutorial that demonstrates how to upload pictures from your local computer using AngularJS directives. As a newcomer to Angular, I followed the instructions but now I'm stuck on modifying it to display the selected ima ...

Code segmentation when accessing memory that has been allocated

I'm struggling to populate a sparse matrix with random elements. I've been attempting to generate random values and assign them to the value, column, and row arrays, but I keep encountering segmentation faults. Oddly enough, this issue only aris ...

Activating the Mobile Menu Function when the Window is Resized

I've developed a JavaScript function that triggers on window resize. When switching between landscape and portrait orientation on mobile devices or tablets, the window dimensions change. This functionality is also useful for browser testing on desktop ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...