arranging the elements of an object by comparing prefixes

I've got an object structured like this:

let fragment = {
    "lcxsm-item-1-heading": "Romeo",
    "lcxsm-item-1-heading-1-subheading": "Lima",
    "lcxsm-item-1-heading-2-subheading": "Zero",
    "lcxsm-item-1-heading-3-subheading": "France",
    "lcxsm-item-1-heading-1-subheading-1-subitem": "Jupiter",
    "lcxsm-item-1-heading-1-subheading-2-subitem": "Sunday",
    "lcxsm-item-1-heading-1-subheading-3-subitem": "Match",

    "lcxsm-item-2-heading": "email",
    "lcxsm-item-2-heading-1-subheading": "password",
    "lcxsm-item-2-heading-2-subheading": "user",
    "lcxsm-item-2-heading-3-subheading": "Italia",

    "lcxsm-item-3-heading": "you",
    "lcxsm-item-3-heading-1-subheading": "Rome",
    "lcxsm-item-3-heading-2-subheading": "Indiana",
    "lcxsm-item-3-heading-3-subheading": "phone",
    "lcxsm-item-3-heading-1-subheading-1-subitem": "number",
    "lcxsm-item-3-heading-1-subheading-2-subitem": "mail",
    "lcxsm-item-3-heading-1-subheading-3-subitem": "id"
}

My aim is to develop a function named "getObjectListWithPrefix" that will provide the following output.

[
  {
    "main-heading": "Romeo",
    "subHeadings": [ "lima", "zero", "france" ],
    "subItems": [ "Jupiter", "Sunday", "Match" ]
  },
  {
    "main-heading": "email",
    "subHeadings": [ "password", "user", "Italia" ]
  },
  {
    "main-heading": "You",
    "subHeadings": [ "Rome", "Indiana", "phone" ],
    "subItems": [ "number", "mail", "id" ]
  }
]

The specific function call I am using is

getObjectListWithPrefix("lcxsm-item-", fragment, "-heading")
. Can the object be iterated using just a prefix and suffix? There are cases where there are headings, subheadings, and sub-items for each subheading. Any assistance would be appreciated!

Answer №1

The first step involves extracting information from a main string and then categorizing it into different groups.

let fragment = { "lcxsm-item-1-heading": "Romeo", "lcxsm-item-1-heading-1-subheading": "Lima", "lcxsm-item-1-heading-2-subheading": "Zero", "lcxsm-item-1-heading-3-subheading": "France", "lcxsm-item-1-heading-1-subheading-1-subitem": "Jupiter", "lcxsm-item-1-heading-1-subheading-2-subitem": "Sunday", "lcxsm-item-1-heading-1-subheading-3-subitem": "Match", "lcxsm-item-2-heading": "email", "lcxsm-item-2-heading-1-subheading": "password", "lcxsm-item-2-heading-2-subheading": "user", "lcxsm-item-2-heading-3-subhea...</answer1></answer1>
<exanswer1><div class="answer accepted" i="67731045" l="4.0" c="1622146969" v="2" a="TnVy" ai="12750399">
<p>To get started, the primary phase is to extract details from a specific string and group them together effectively.</p>
<p><div>
<div>
<pre class="lang-js"><code>let fragment = { "lcxsm-item-1-heading": "Romeo", "lcxsm-item-1-heading-1-subheading": "Lima", "lcxsm-item-1-heading-2-subheading": "Zero", "lcxsm-item-1-heading-3-subheading": "France", "lcxsm-item-1-heading-1-subheading-1-subitem": "Jupiter", "lcxsm-item-1-heading-1-subheading-2-subitem": "Sunday", "lcxsm-item-1-heading-1-subheading-3-subitem": "Match", "lcxsm-item-2-heading": "email", "lcxsm-item-2-heading-1-subheading": "password", "lcxsm-item-2-heading-2-subheading": "user", "lcxsm-item-2-heading-3-subhea...</answer1>
<exanswer1><div class="answer accepted" i="67731045" l="4.0" c="1622146969" v="2" a="TnVy" ai="12750399">
<p>In the beginning, you need to retrieve information from a specified string and then group them accordingly.</p>
<p><div>
<div>
<pre class="lang-js"><code>let fragment = { "lcxsm-item-1-heading": "Romeo", "lcxsm-item-1-heading-1-subheading": "Lima", "lcxsm-item-1-heading-2-subheading": "Zero", "lcxsm-item-1-heading-3-subheading": "France", "lcxsm-item-1-heading-1-subheading-1-subitem": "Jupiter", "lcxsm-item-1-heading-1-subheading-2-subitem": "Sunday", "lcxsm-item-1-heading-1-subheading-3-subitem": "Match", "lcxsm-item-2-heading": "email", "lcxsm-item-2-heading-1-subheading": "password", "lcxsm-item-2-heading-2-subheading": "user", "lcxsm-item-2-heading-3-subheading": "Italia", "lcxsm-item-3-heading": "you", "lcxsm-item-3-heading-1-subheading": "Rome", "lcxsm-item-3-heading-2-subheading": "Indiana", "lcxsm-item-3-heading-3-subheading": "phone", "lcxsm-item-3-heading-1-subheading-1-subitem": "number", "lcxsm-item-3-heading-1-subheading-2-subitem": "mail", "lcxsm-item-3-heading-1-subheading-3-subitem": "id", }

let result = [];

for (const key_str in fragment) {
    let keys = key_str.split("-");
    let titel = keys[keys.length - 1];
    let index = keys[2] - 1;
    let value = fragment[key_str];

    if (titel == "heading") {
        result[index] = { "main-heading": value }
        continue
    }

    result[index] ??= {};
    result[index][titel] ??= []
    result[index][titel].push(value)
}

console.log(result)

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

Generate a link using the current webpage's address

My latest project is a bilingual website that utilizes two separate databases. The website can be accessed in English at www.martyregan.com/ and in Japanese at www.martyregan.com/jp/. Currently, the language choice can be made using flags, but the links on ...

The clearTimeout function in React stateless components does not appear to be functioning properly

I am facing an issue with a component that I developed. In this component, one value (inclVal) needs to be larger than another value (exclVal) if both are entered. To ensure that the function handling this comparison doesn't update immediately when pr ...

Maintaining Login State in Django REST API After Page Refresh

Struggling with maintaining login status when using DJANGO Rest API and an AngularJS client. Despite having authtoken and default auth classes set up, including 'rest_framework.authentication.TokenAuthentication' and 'rest_framework.authenti ...

Error: The parser did not expect a closing curly brace

I'm working on a jQuery script that adds an input button to the body and then assigns it an onclick function. The function being called should take two arguments, both variables defined earlier in the code. Here's the current code snippet I have ...

Call a function of a javascript object from inside a callback function

In a user script, I have defined the MyClass and its methods as follows: function MyClass() { this.myCallback = function() { alert("MyClass.myCallback()"); }; this.startRequest = function() { GM_xmlhttpRequest({ &a ...

Navigating through columns of a connected SQL table for JSON retrieval

In my PHP script, I have implemented the following SQL query: SELECT * FROM national_age_gender_demographics INNER JOIN arizona_age_gender_demographics WHERE national_age_gender_demographics.age_group = arizona_age_gender_demographics.age_group ORDER B ...

Tips on running methods consecutively within ngOnInit in Angular

I'm currently working on an ngoninit function that contains four methods. Two of these methods are responsible for retrieving data from the API, while the other two are intended to load this data when the page loads. ngOnInit(){ getname(); getsubjects ...

"Interactive table feature allowing for scrolling, with anchored headers and columns, as well as the option to fix

I'm in need of a table that has certain requirements, as shown in the image. https://i.stack.imgur.com/Z6DMx.png The specific criteria include: The header row (initially blurred) should remain fixed when scrolling down the table The first column s ...

Navigating to a subset in PHP, depending on a specific value

I want to organize array items into sub-arrays based on a specific value. Here's an example: Array ( [0] => Array ( [Desc] => 'Sub category' [SubID] => null ) [1] => Array ( [Desc] ...

How can one efficiently allocate and access a dynamically sized array of pointers in C++?

Let's say we have *line[30]; To allocate a string of 81 characters for each pointer, one way to accomplish this is by using dynamic memory allocation. This can be done with the help of functions such as malloc(). Once the memory is allocated, you c ...

Rendering based on certain conditions and executing in React applications

I am working on my React app and utilizing Material Datatable. I want to conditionally render a specific part of the code only if data is not null or undefined. I am also open to not executing the Object.entries(data).map(x => ( line. <TableBody > ...

Warning: Unhandled promise rejection - Error encountered while trying to add response due to inability to set headers after they have already been sent to the client

After including the line res.status(201).json({ email });, I encountered an error message saying UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. How can I address this issue? Here is a ...

Terminate or flag an AJAX request upon receiving a 200 OK response from the browser

My request is as follows: // =============================================== start() // // clicked_button : the user click the start button. // app_path : the app path // // return none. // var start = function(clicked_button, app_path) { $.aja ...

Reduce the version of NodeJs and express

At the moment, I am tackling a nodejs project. I have Express 3.X installed, which is currently in its alpha stage, and my node version is also at 0.7.2-pre. I am currently attempting to lower my express version through npm, but it appears that I also need ...

Unable to retrieve information from the request

I'm having trouble retrieving data from a JSON request. I can successfully fetch data with getDrivers(), but when I attempt to retrieve data using getDriverRaces($scope.id), nothing is returned. I tried the manual approach: http://ergast.com/api/f1/20 ...

Tips for obtaining the necessary value input upon clicking?

Let's consider a scenario where you have the following JavaScript code: function openAlbum() { $("#tracks").html('Some text...'); var uid = $("#uid").val(); $.ajax({ type: "POST", url: "s.php", ...

What is the best way to trigger a child function from the parent component in React?

In my React application, there are three components: two child components and one parent component. I need to pass data (projectId) from ChildOne to ChildTwo through the Parent component and trigger a function once the data is received. Essentially, I am s ...

In C#, generate a byte array containing both integer and hexadecimal values

I am working on creating a byte array that includes both hexadecimal and integer values. For instance: int value1 = 13; int value2 = 31; byte[] mixedbytes = new byte[] {0x09, (byte)value1, (byte)value2}; Issue: The value 31 is being converted to 0x1F in ...

Sending data to callback functions

In the process of developing a jQuery plugin designed to be applicable to a selector, I encountered a challenge related to maintaining the current context item within the each loop of the selector. The plugin involves making multiple calls to webservices w ...

Avoiding the storage of POST data in JSON format

Here is some code I am working with: var jsonString = "some string of json"; $.post('proxy.php', { data : jsonString }, function(response) { var print = response; alert(print); }); And this P ...