Overhauling JSON Data Output in Angular Version 2 and beyond

Currently, I am dealing with a complex web API JSON response that contains nested data. I would like to simplify the structure by extracting only the necessary information.

How can I achieve this using Angular 2+/Typescript?

I would greatly appreciate any guidance.

Imagine I have the following data:

"O1": {
    "P1": "Something",
    "A1": [{
       "P2": "Something",
       "A2": [{
         "P3": "Something"
        }]
    }],
    "P4": "Something"
}

and my goal is to restructure it as follows:

"O1": {
    "P1": "Something",
    "P2": "Something",
    "P3": "Something"
}

Is it possible to reconstruct the model within a class constructor? I haven't had any luck finding relevant resources online so far.

Please let me know if you need more information from me.

Thank you.

Answer №1

We can utilize a method to flatten the original object based on a suggested code snippet. Following that, we can refine our selection by filtering out specific properties for inclusion in the finalized object:

 function filterObj(obj: any, propsForFilter: string[]) {
  const result = {};
  for (let prop in obj) {
    const filteredProp = propsForFilter.find(p => prop.includes(p));
    if (filteredProp) {
      result[filteredProp] = obj[prop];
    }
  }
  return result;
}
const flattened = flattenObject(obj);
console.log(flattened, filterObj(flattened, ['P1', 'P2']));

The filterObj function allows for specifying an array of properties to be included in the final outcome. I trust this approach proves beneficial to your requirements.

Answer №2

Just stumbled upon this code snippet on GitHub: https://gist.github.com/penguinboy/762197

function convertObjectToFlat(ob) {
    let flatObj = {};

    for (let key in ob) {
        if (!ob.hasOwnProperty(key)) continue;

        if ((typeof ob[key]) === 'object') {
            let nestedFlatObj = convertObjectToFlat(ob[key]);
        
            for (let nestedKey in nestedFlatObj) {
                if (!nestedFlatObj.hasOwnProperty(nestedKey)) continue;

                flatObj[key + '.' + nestedKey] = nestedFlatObj[nestedKey];
            }
        } else {
            flatObj[key] = ob[key];
        }
    }
    
    return flatObj;
}

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

Chart Subscription Established but Alerts Not Being Dispatched

After successfully creating my GraphServiceClient subscription on my user, I initially received a positive response. The JSON data for the subscription included information such as the resource, change type, client state, notification URL, expiration date/ ...

Prepending the emulated prefix to Angular 6-7 ViewEncapsulation

Can we customize the tags generated when using ViewEncapsulation.Emulated in an Angular 2-7 component? Currently, it generates tags like [_ngContent-C0], but is there a way to add a custom string to the generated tag, such as [_ngContent-C0-myApp]? Thank ...

Extract information from a complex nested structure within an array

Can someone assist me with extracting only the username from the response provided below? I am able to access other data but struggling with this particular aspect. [ { "_id": "5f44d450aaa72313549d519f", "imageTitle": "u ...

Protected class, yet not transferable

My output varies based on the type of input provided. I have a custom guard in place to protect the input, but I'm still having trouble assigning it to the declared output: type InputType<Sub extends SubType> = { a: Sub, b: string } type SubTyp ...

Setting up the cypress-grep plugin version 3.1.0 on Cypress v11.01: A Step-by-Step Guide

Cypress Version 11.0.1 Node Version 16.16.0 Package Manager Yarn version 1.22.19 Operating System Windows 10 Pro Version 21H2 To practice using the Cypress grep plugin, I have set up a test project called cypress_grep_test_project. I have modified som ...

Having trouble launching my angular application in the development environment

My Angular application builds and runs successfully in production mode, but I'm facing issues running it in development mode. When I try the command: npm exec ng serve -c dev --port 4200 --proxy-config proxy.conf.json and add -c dev, I encounter an er ...

Parsing JSON data with white space in resource objects

In the JSON string, the Resource Objects have a whitespace causing 'id' to be filled, but 'use id', 'user status', and 'last event' are null. I attempted 3 different approaches in my class, none of which were succes ...

How to effectively utilize JSON responses with jQuery Mobile?

I've been facing an issue with working on my JSON result in JavaScript. Can anyone provide some insight? Even though the JSON call returns a success status code (200) and I can view the data in Firebug, no alert is being displayed. $(document).on(& ...

Sending an Ajax request with JSON data to a PHP script to receive multiple values in

After following numerous tutorials and questions on the website, I attempted to retrieve an array from an ajax call to a PHP function using 'echo json_encode()' The root of my issue seems to be in the JS code JavaScript Code.... var pid = 23; ...

Angular: Incorporating a custom validation function into the controller - Techniques for accessing the 'this' keyword

I'm currently working on implementing a custom validator for a form in Angular. I've encountered an issue where I am unable to access the controller's this within the validator function. This is the validator function that's causing tr ...

Leveraging Cereal for parsing a JSON string

Seeking guidance on deserializing a JSON string in Cereal as I am navigating this process for the first time. Unfortunately, my access to Google Groups is restricted by my work firewall, preventing me from seeking help on the message board. I have managed ...

What is the relationship between an odd number and the value 1 in JavaScript that results in a 'true' outcome?

I encountered a straightforward problem, but the solution has left me perplexed. function transformArray(numbers) { // If 'i' is an odd number, i & 1 will evaluate to 1 or true return numbers.map(i => (i & 1) ? i * 3 : i * 2); } co ...

The guard check may not be enough to prevent the object from being null

Hello, I am facing an issue with the Object is possibly "null" error message in my Node.js + Express application. How can I resolve this problem? REST API export const getOrderReport = async ( req: Request<{}, {}, IAuthUser>, res: Resp ...

Deleting and inserting an element in the Document Object Model

I am currently working on developing a framework and need to create a directive called cp-if. Unlike the existing cp-show directive, where I can simply change the visibility of an element to 'none' and then make it visible again, with the cp-if d ...

Creating a model and assigning values in TypeScript

I am currently developing an angular application and need to send data to a post API. The JSON structure I am working with is as follows: { "name": "julie", "id": 1, "PersonalDetails": { "hom ...

angular contains vulnerabilities of a moderate severity level

I am encountering an issue while trying to set up the json server for a web application I am developing using Angular. Can someone provide assistance in resolving this problem? The following dependencies are at risk due to vulnerable versions: node_m ...

the value of properrty becomes undefined upon loading

In my code, there exists an abstract class named DynamicGridClass, containing an optional property called showGlobalActions?: boolean?. This class serves as the blueprint for another component called MatDynamicGridComponent, which is a child component. Ins ...

Steps for writing code to append and execute code snippets using values from a JSON dataset

My attempt to fetch the result through this code is I am looking to display 'Y' or 'N' in the columns Mon, Tue, Wed, Thu, Fri, Sat, Sun I am facing issues fetching the 'run' value from the json data. I have used user.days to ...

npm is asking for a peer to be installed, but none was found

I am facing some warnings that I can't seem to resolve. Despite my attempts at installing the required dependencies, I have not been successful. npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e0f041843050b171901 ...

I'm having trouble viewing the unique Google Map design on my application

I have recently customized Google maps following the guidelines in this documentation: https://developers.google.com/maps/documentation/javascript/styling For styling, I utilized the Cloud tool and opted for the available template instead of using JSON st ...