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

Can Googlebot detect changes made to an HTML <title> tag using JavaScript?

Within my website, I have a search engine that operates using ajax technology. My goal is to assign a unique <title> for every search request made. This involves modifying the title each time I receive a response from the ajax feature. I am wonderin ...

NodeJS: Issue with Route is disrupting the functionality of the Restful API

Struggling to develop an API using Node.js and Express, encountering routing issues with express.Router(). Take a look at my code below: Server.js file contents: // Get necessary packages var express = require('express'); var app = express(); ...

Is it possible to maintain HTML, JS, and CSS files as separate entities when developing Vue.js components, similar to how it is

Is it possible to maintain separate HTML, JS, and CSS files while creating Vue.js components? I recently read the "Why Vue.js doesn't support templateURL" article which discusses this topic. "Proper modularization is a necessity if you want to bu ...

What is the best way to determine the accurate true or false outcome from a JSON assertion in JMeter?

Our task involves the identification of "elements" and then determining whether they are true or false. { "first": { "second": [ { "element": 1, "elementrec": null, "enabled": true, ...

Press one button to activate another button

I am looking to activate a button's class by clicking on another button. The button I have is: <button class="clear-cart banner-btn">clear cart</button> This button is used for clearing a cart. On the order confirmation page, I click on ...

jQuery's visibility check function is not functioning properly

I am developing a web application for managing orders and finance in a restaurant. To enhance the functionality of my application, I require more screens to operate with. To facilitate this, I have implemented a small function to toggle between visibility: ...

Tips on customizing the MSAL login commands for successful integration with numerous users

Successfully implemented the code to login using a username and password combination with Cypress for a webapp integrated with MSAL. In the end-to-end Testfile: describe('Login with MSAL as xxUsername', () => { beforeEach(() => { cy.Lo ...

What are the steps for performing a self-triggered AJAX post request?

I have been exploring self-invoked functions and recently used an http.get function to retrieve data from a JSON file like this: var Callmodule = (function(){ var urljsonEntrata= "modello.json"; function getmodules(){ var req = $.ajax({ url: ...

Error encountered while attempting to make AJAX call: "`$.ajax` parse error on JSON object: {"vErrorsFound":true,"vMessage"

I am trying to update my code from using jQuery 1.3.2 to jQuery 1.5, but I am facing issues with parsing JSON data. I have a PHP script that returns the following JSON object using json_encode: {"vErrorsFound":true,"vMessage":"Login Failed"} I have exper ...

Error encountered: A syntax error occurred due to an unexpected token ":" found in the file path D:practise odejs odejs-demoviewsindex.html

Attempting to switch the engine view from .ejs to .html resulted in an error. After searching online, I was unable to find a solution for the following problems: Express 500 SyntaxError: Unexpected token : in D:\practise\nodejs\nodejs-demo& ...

What could be causing my JQuery code to fail after loading data via ajax?

My tree view is set up using the following jQuery code: $(".treeView").on("click", ".CollOpen, .CollClosed", function () { $(this).toggleClass("CollOpen CollClosed").nextAll('ul').first().toggle(); }); Initially, this code works perfectly. ...

Exploring ways to track file upload progress with the Fetch API in ReactJS or NextJS

Currently, I am utilizing Nextjs for constructing a full-stack application. Specifically, I am focusing on the admin CMS part and attempting to implement file uploads such as images. Referring to this modified version of the code from this post. The upload ...

Methods like jQuery blink(), strike(), and bold() offer dynamic ways to manipulate

I'm currently tackling an inquiry. The code I crafted seems to be functioning without any issues: (function () { if($('#target:contains("bold")')) { $('#target span:first').css('font-weight','bold ...

Using AJAX, JQuery, and PHP to convert a given name to match the columns in a query, utilizing the data sent

One thing that I'm wondering about is how PHP handles my ajax requests. For example, consider the following code snippet: $("#addUser").on('click', '.btnAddSubmitFormModal', function() { $.post("add.php", { ...

Difficulty closing Modal Popup when multiple Modals are displayed simultaneously

I am facing a challenge with transitioning between modal screens When the button on the screen is clicked, Modal1 opens: $modal.open({ templateUrl: 'abc.html', controller: 'abcCtrl', size: 'lg', scope: $scope ...

Inconsistencies in latency experienced when making calls to Google Sheets V4 API

Recently, I've been encountering latency issues with the following code: var latency = Date.now(); const sheetFile = await google.sheets({version: 'v4', auth}); var result = await sheetFile.spreadsheets.values.get({spreadsheetId: shee ...

Creating a reusable anonymous self-invoking function

Here is a function that I am working with: (function(e, t) { var n = function() { //code, code, code }; //code, code, code e.fn.unslider = function(t) { //code, code, code }; })(jQuery, false) To execute this function, I have impleme ...

Resetting a Material UI search filter TextField back to its initial state after clearing it

Unleashing the power of ReactJS alongside Material UI has been a journey of ups and downs for me. While I managed to create a versatile search filter component for my data tables that worked like a charm, I now find myself at a crossroads. My new goal is t ...

Radio button triggers an ajax call once, but then fails to function

How can I troubleshoot an issue where the ajax function only works once when clicking on a radio button to change its value from 0 to 1, but not back to 0? The form contains a table with radio buttons for each record, and clicking on them triggers the aj ...

Adjusting the font color when hovering over multiline text

I am currently in the process of coding a website for my job, and I am working on changing the text color when it is hovered over. However, there seems to be a break in my code causing the text not to highlight all at once. Any guidance or suggestions on h ...