Unraveling Objects: Simplifying object structures in JavaScript using AngularJS

I received an object from the backend and I need to extract its elements to attach them to the scope for viewing. The structure of the object is as follows:

{
    "Name": {
        "S": "Jon Snow"
    },
    "Location": {
        "S": "Winterfell"
    },
    "Details": {
        "M": {
            "Parents": {
                "M": {
                    "mother": {
                        "S": "Lynna Stark"
                    }
                }
            },
            "Dog": {
                "N": "Ghost Snow"
            }
        }
    }
}

Since I'm unsure of the type of object received, my goal is to convert it into a plain JSON object like this:

{
"Name": "Jon Snow",
"Location": "Winterfell",
"Details": {
    "Parents": {
        "mother": "Lynna Stark"
    },
    "Dog": "Ghost Snow"
}

}

I would appreciate any help, especially since I am new to AngularJS. Can someone also explain the nature of the object I received? Thank you in advance.

Update 1: Thank you for the responses. I now understand the concept. My next question is how can I flatten the object by one level without altering the original backend response, which may vary each time?

Answer №1

const information = {
    "Name": {
        "S": "Jon Snow"
    },
    "Location": {
        "S": "Winterfell"
    },
    "Details": {
        "M": {
            "Parents": {
                "M": {
                    "mother": {
                        "S": "Lynna Stark"
                    }
                }
            },
            "Dog": {
                "N": "Ghost Snow"
            }
        }
    }
}

const flattenData = (information) =>{
  if(typeof information === "string") return information;
  for(let key in information){
    for(let deepKey in information[key]){
      if(deepKey.length === 1){
        const tempData = information[key]
        information[key] = flattenData(tempData[deepKey])
      }
    }

  }
  return information;
}

console.log( JSON.stringify(flattenData(information), null, "\t"))

JS Playground

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

The Mongoose save functionality is failing to work and is resulting in an empty {} object being returned

I've been working on constructing an Auth API with Mongo and Nodejs. The initial setup is complete, but I'm encountering an issue. When I make a request to the register API, it returns an empty object. Here's a snippet of my schema: con ...

Running tests in JavaScript that are similar to Python's doctests

Are there any JavaScript testing frameworks that offer a similar functionality to Python's doctest? function multiply(x, y) { /** Returns the product of `x` and `y`: > multiply(4, 3) 12 The function handles string inputs by convert ...

Having trouble with jQuery's 'OR' not functioning properly when iterating through mandatory input elements

In the process of creating a fallback for required HTML5 attributes for different input types, I encountered an issue with checking the ':checked' status of radio buttons and using the 'OR' || operator within the loop: if (self.val() = ...

Can you modify a attribute value in one HTML file from another?

I currently have a website and I am looking to modify the aria-expanded value of an expandable paragraph on another page when I click on an anchor element in the main page. What changes do I need to make in my main.html file in order to update the aria-exp ...

Encountering 'undefined' issue with find operation in mongoDB

Seeking assistance to utilize all available values in my code. bericht.find({ room: room }).toArray(function(err, docs) { assert.equal(err, null); str2 = str2 + docs.message; The function I'm using can successfully loca ...

Avoiding line breaks when submitting data through Ajax calls is achievable by using the `.val` method

I've come across multiple articles discussing ways to add line breaks to the .val in jQuery, but unfortunately none of them have worked for me. I attempted using the recommended workaround provided by jQuery: $.valHooks.textarea = { get: function( ...

What steps can I take to make sure that a sub component's props are refreshed properly?

I'm encountering an issue with RTK queries in my project. I have a parent component that contains a table component. When a refresh event occurs, such as deleting data, the parent component receives updated data and passes it down to the child compone ...

Transmitting HTTP headers using Node.js

Within my Node JS Express application, I have an API endpoint called 'download' that returns a buffer to the calling application along with a header named 'status', which is a Javascript object. The response from Node sends the buffer ...

How to manage the three states (InProgress, Success, Error) of a dropdown dynamically in AngularJS with ng-show/hide?

Currently, I have implemented a bootstrap dropdown that loads a list of countries by making an external API call. My goal is to display three different states of behavior (progress, success, error) in the dropdown using ng-show/hide. However, I am unsure h ...

Exploring the concept of ng-model with undefined values in AngularJS

Having an input with a $watch function that updates a search query in real time through AngularJS, I am encountering an issue. Despite setting the initial value of the model to empty, it automatically triggers the search and displays results. My concern i ...

Error: Trying to break down a non-iterable object is not valid

Currently working on an Ionic React app and encountering the following error: Error: TypeError - Invalid attempt to destructure non-iterable instance Once I run the program, the error occurs at this point: . Shown below is a snippet of my code: import ...

Getting around using Material-UI Icons

Is it possible to utilize a Material-UI Icon for navigation using React Router Dom? I attempted the following approach without success: <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon> With buttons, I am able to use component={Link ...

What is the best way to manage the "checked" state of an input checkbox using React?

I'm currently developing an application that features a form with radio buttons. One of the radio button options can be toggled on/off using a checkbox, but I want to ensure that the checkbox is disabled if the corresponding radio button is not selec ...

adjust variable increment in JavaScript

As I work on developing a Wordpress theme, I have encountered an issue with incrementing a load more button using Javascript. This is my first time facing this problem with a javascript variable, as I don't always use Wordpress. The variable pull_page ...

The angular 5 application encountered an issue where it was unable to access the property 'singlePost' due to a null value, resulting

When using the once method to fetch data from the Firebase database, everything works correctly. However, when I try to use the on method, I encounter an error that says: ERROR TypeError: Cannot read property 'singlePost' of null. How can I prope ...

Connection between mapStateToProps and mapActionsToProps failing to trigger in react component

I am facing an issue with my component (SearchFilter.js) where the connect method is not triggering mapStateToProps and mapActionsToProps on export. The problem is that mapStateToProps is not firing at all -- no props (neither state nor actions) are showi ...

After installing Ember and running the Ember server, I noticed that the node_modules directory appears to be empty. This issue is occurring on my Windows 10 x64 PC

Welcome to the command console: C:\Users\Documents\emberjs>ember server node_modules seem to be empty, consider running `npm install` Ember-cli version: 2.14.2 Node version: 6.11.2 Operating System: Windows 32-bit x64 I'm a beg ...

Conditions must fail for window.location to execute

<a href="www.google.com" class="social" id="social">Click here for Link one</a> <a href="www.cnn.com" class="social" id="social">Visit Link two now!</a> <a href="www.facebook.com" class="social" id="social">This is Link thre ...

The NoUiSlider had already been initialized

Currently, I am facing an issue when trying to incorporate noUiSlider with Angular JS. I have a directive that contains 4 sliders and I intend to display this directive on 2 different pages. However, each time I switch between the pages, an error occurs st ...

Ways to separate a portion of the information from an AJAX Success response

I am currently working on a PHP code snippet that retrieves data from a database as follows: <?php include './database_connect.php'; $ppid=$_POST['selectPatientID']; $query="SELECT * FROM patient WHERE p_Id='$ppid'"; $r ...