Creating a fresh JSON structure by utilizing an established one

I have a JSON data that contains sections and rubrics, but I only need the items for a new listing. The new object named 'items' should consist of an array of all the items.

The final JSON output should be sorted by the attribute 'name' and resemble this structure:

{
  "items": [
    {
      "id": 10000006,
      "name": "Boah"
    },
    {
      "id": 10000013,
      "name": "Gut"
    },
    {
      "id": 10000003,
      "name": "Ipsum"
    },
    {
      "id": 10000001,
      "name": "Lorem"
    },
    {
      "id": 10000005,
      "name": "Lorum"
    },
    {
      "id": 10000004,
      "name": "Name"
    },
    {
      "id": 10000002,
      "name": "Stet"
    }
  ]
}

To create the new JSON, I am provided with the following source data:

{
  "sections": [
    {
      "name": "FooBar",
      "rubrics": [
        {
          "name": "Foo",
          "items": [
            {
              "id": 10000001,
              "name": "Lorem"
            },
            {
              "id": 10000002,
              "name": "Stet"
            },
            {
              "id": 10000003,
              "name": "Ipsum"
            }
          ]
        },
        {
          "name": "Bar",
          "items": [
            {
              "id": 10000004,
              "name": "Name"
            },
            {
              "id": 10000005,
              "name": "Lorum"
            },
            {
              "id": 10000006,
              "name": "Boah"
            }
          ]
        }
      ]
    },
    {
      "name": "BlahBloob",
      "rubrics": [
        {
          "name": "Bla",
          "items": [
            {
              "id": 10000013,
              "name": "Gut"
            }
          ]
        },
        {
          "name": "Bloob",
          "items": [
            {
              "id": 10000014,
              "name": "Name"
            },
            {
              "id": 10000015,
              "name": "Lorem"
            }
          ]
        }
      ]
    }
  ]
}

Any suggestions on how to achieve this using plain JavaScript or perhaps TypeScript?

Thank you for taking the time to read my question. Your help is greatly appreciated!

Answer №1

To retrieve the items, simply loop through each rubric in every section of your source file. Once you have gathered all the items, just sort them based on their names and you're good to go.

This code snippet makes use of ES6 syntax, but can be easily translated into ES5 if required.

function getItems(source) {
  const itemsList = [];

  for (const section of source.sections) {
    for (const rubric of section.rubrics) {
      itemsList.push(...rubric.items);
    }
  }

  itemsList.sort((a, b) => a.name.localeCompare(b.name));

  return { itemsList };
}

Answer №2

Utilizing a more practical approach involves utilizing the map and reduce functions to select the rubrics and combine them together.

data.sections
  .map(section => section.rubrics) // extracting rubrics
  .reduce((a, b) => a.concat(b)) // merging rubrics
  .map(rubric => rubric.items) // obtaining items from each rubric
  .reduce((a, b) => a.concat(b)) // merging items
  .sort((a, b) => a.name.localeCompare(b.name)); // sorting

Answer №3

const transformObject = (oldObj) => {
    let newObj = {
        "items": []
    };

    oldObj.sections.forEach((section) => {
        section.rubrics.forEach((rubric) => {
            rubric.items.forEach((item) => {
                newObj.items.push(item);
            });
        });
    });

    newObj.items = newObj.items.sort((a, b) => {
        if (a.name < b.name) { return -1; }
        if (a.name > b.name) { return 1; }
        return 0;
    });
    return newObj;
}

You can easily convert JSON to objects and vice versa by using the methods JSON.parse() and JSON.stringify().

Answer №4

Here's a potential solution

var data ={
"sections": [
{
"name": "FooBar",
"rubrics": [{"name": "Foo", "items": [{"id": 10000001,"name": "Lorem"}, {"id": 10000002,"name": "Stet"}, {"id": 10000003,"name": "Ipsum"}]
}, {
"name": "Bar",
"items": [{
"id": 10000004,
"name": "Name"
}, {
"id": 10000005,
"name": "Lorum"
}, {
"id": 10000006,
"name": "Boah"
}]
}]
}, {
"name": "BlahBloob",
"rubrics": [{
"name": "Bla",
"items": [{
"id": 10000013,
"name": "Gut"
}]
}, {
"name": "Bloob",
"items": [{
"id": 10000014,
"name": "Name"
}, {
"id": 10000015,
"name": "Lorem"
}]
}]
}]
};
var itemObj = {};
var itemArr = [];
var sections = data.sections;
for(var i=0;i<sections.length;i++)
{
  for(var j=0;j<sections[i].rubrics.length;j++){    
    for(var k=0;k<sections[i].rubrics[j].items.length;k++){      
      var itemObj;
      itemObj['id'] = sections[i].rubrics[j].items[k].id;
      itemObj['name'] = sections[i].rubrics[j].items[k].name;      
      itemArr.push(itemObj);
    }
  }
}
var finalObj = {"items":itemArr};
console.log(finalObj);

JSFiddle Link

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

Guide to utilizing element reference with material UI components in Angular

I am facing difficulty in accessing the reference of an element. My intention is to wrap the material UI elements within a div and set the opacity: 0 so that it remains hidden in the HTML, allowing me to handle the value in my component.ts file. The main g ...

Aptana - Expose the Declaration

After hearing rave reviews about Aptana being the best IDE for JavaScript, I decided to download it. I grabbed a project from GitHub, found a method call in the code, right clicked on it, and saw 'open declaration - F3'. However, when I tried bot ...

Is it feasible to verify the accuracy of the return type of a generic function in Typescript?

Is there a way to validate the result of JSON.parse for different possible types? In the APIs I'm working on, various Json fields from the database need to have specific structures. I want to check if a certain JsonValue returned from the database is ...

utilizing PHP to transform a JSON string into an array

I am facing an issue with json parsing and despite researching extensively on Stackoverflow, I cannot seem to figure out what I am doing wrong. On my website, I utilize the Facebook API to post my feed using curl, which returns a json message. I store thi ...

Issue with Angular Unit Test: Provider for WebSocketAPI is missing

I am encountering some failing unit tests in my Angular 10 application due to the following error message: Failed: R3InjectorError(DynamicTestModule)[WebSocketAPI -> WebSocketAPI]: NullInjectorError: No provider for WebSocketAPI! Typically, this type ...

What is the best way to make sure the embedded object fills the entire height of the container div?

I am currently using angular2/4 along with angular-material (https://material.angular.io/). My challenge lies in trying to embed a PDF within it. The issue I am facing is that the height of the PDF object seems to be small and doesn't fully occupy the ...

When transitioning to an object, Vue.js fails to refresh

My component contains an object called elements: elements: { id: { text: '', color: '', ... } To modify it, I use: <a-textarea autoFocus placeholder="text to include" :style="{ width: &ap ...

Preserve the scroll location while adding new content to a list in AngularJS

I have been attempting to add new items to a list within a scrollable container using ng-repeat, with the most recent item appearing at the top. It is important that I am able to preserve the scroll position if the scrollbar is not at the very top when add ...

Problem with C# HTTP Post Curl functionality

I am having difficulty understanding how to correctly perform a specific HTTP Post request in C#. I believe I am close to getting it right, but I keep encountering issues along the way. Here is the request I am trying to make: curl -i -X POST -H 'Con ...

The luminosity of MeshBasicMaterial in Three.js

In my current setup with threejs, I am utilizing MeshBasicMaterial for lighting effects. Each element contains a simulated point light within. I have assigned a variable named color, defined as rgb(random value, random value, random value). I am looking ...

Ways to intercept a POST request from a different web service

https://i.sstatic.net/sMXIr.jpg I am currently utilizing Block.io Web Hooks for my notification service. According to the documentation, it is necessary to communicate through POST requests and all notification events will adhere to a specific JSON object ...

Nodemailer is functioning properly in a local environment, however, it is encountering issues when

I am facing an issue with Nodemailer where it is sending emails successfully on my local machine but not on Lambda. I have tried various solutions from Stack Overflow, but none of them seem to be working for me. One suggestion was to make the sendEmail fun ...

The browser displays the jQuery ajax response instead of passing it to the designated callback function

I have a web application that connects to another web service and completes certain tasks for users. Using codeigniter and jQuery, I have organized a controller in codeigniter dedicated to managing ajax requests. The controller executes necessary actions ...

Images Are Failing to Load on the Webpage

I'm facing an issue with appending pictures of restaurants to dynamic div IDs. When I make the div ID static, the pictures show up fine from the server, but when I try to make it dynamic, the images don't get appended. Can someone please assist m ...

Querying JSON data within a PostgreSQL database that contains embedded JSON objects

I'm a beginner with postgres and facing difficulties in finding an example of how to query the following: { "Skill": { "Technical": [ { "Name": "C#", "Rating": 4, "Last Used": "2014-08-21" } ...

Typescript - optional type when a generic is not given

I am hoping for optionalFields to be of type OptionalFieldsByTopic<Topic> if a generic is not provided, or else OptionalFieldsByTopic<T>. Thank you in advance for the assistance. export interface ICreateItem<T extends Topic = never> { // ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Fetching JSON data with Ajax is successful, but the information is not being displayed

I am struggling to showcase Json data from a URL in a table using ajax. The aim is for the code to iterate through the data and present it neatly in a table. <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/a ...

What is the reason behind the absence of compile time errors when using 'string' functions on an 'any' field type variable in TypeScript?

Looking at the following typescript code snippet: let a; a = "number"; let t = a.endsWith('r'); console.log(t); It is worth noting that since variable 'a' is not declared with a specific type, the compiler infers it as ...

javascript: update hidden field if date is past January 15th

Having a bit of trouble with this one after a full day! The form contains a hidden field called 'grant_cycle'. If the form is submitted after January 15th, it should have the value 'Spring, [year]', or if after July 15th, it should be ...