converting nested object structures in typescript

I'm trying to flatten a nested object in my Loopback and Typescript controller

Here's the structure of my model :

export class SampleModel {
  id: number;
  code: number;
  guide?: string;
  gradeData?: string;
}

Take a look at this example object :

{
  "id": 1,
  "code": 12345,
  "guide": "Guide for 2021",
  "gradeData": {
    "en": "Eng grade",
    "de": "Ger grade"
  }
}

This is how my controller function looks like:

// returns an array of SampleModel objects
@get('/guides')
async find(
@param.query.string('lang') lang: string,
@param.filter(SampleModel) filter?: Filter<SampleModel>
): Promise<SampleModel[]> {
return this.sampleModelRepository.find(filter); //this returns Promise<SampleModel[]>
}

I aim to modify the response based on the lang parameter. For instance, if lang = en, I want the output to be like:

[
  {
    "id": 1,
    "code": 12345,
    "guide": "Guide for 2021",
    "gradeData": "Eng grade"
  }
]

Answer №1

Is this what you were thinking of? Certainly, the langcode should be flexible.

[{
  "id": 1,
  "code": 12345,
  "guide": "Guide for 2021",
  "gradeData": {
    "en": "Eng grade",
    "de": "Ger grade"
  }
}].map(e=>{
    e.gradeData = e.gradeData["en"];
    return e;
})

Resulting object:

[
    {
        "id": 1,
        "code": 12345,
        "guide": "Guide for 2021",
        "gradeData": "Eng grade"
    }
]

Answer №2

I owe a big thanks to @Firewizz for helping me achieve this. Behold, my recently updated controller:

  // fetching an array filled with SampleModel instances
  @get("/guides")
  async find(
    @param.query.string("lang") lang: string,
    @param.filter(SampleModel) filter?: Filter<SampleModel>
  ): Promise<SampleModel[]> {
    const result = this.sampleModelRepository.find(filter); //this yields Promise<SampleModel[]>
    if (lang != null) {
      (await result).map((element) => {
        if (element.gradeData !== null && element.gradeData.hasOwnProperty(lang)) {
          element.gradeData = new Map(Object.entries(element.gradeData)).get(language);
          // the necessity of this part is puzzling; attempting alternative method leads to compilation error " Element implicity has an 'any' type because index expression is not of type 'number' " possibly due to gradeData being defined as a String although when I execute
          // console.log(typeof element.gradeData)
          // it returns object

          // Other attempted solutions include:
          // `element.gradeData = element.gradeData[language];`
          // resulting in SyntaxError: Unexpected token o in JSON at position 1 which may be because it's already an object

          // Then there was
          // `element.gradeData = JSON.parse(JSON.stringify(element.gradeData))[language];`
          // though converting it into a map seemed like a better workaround
        }
        return element;
      });
    }

    return 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

Utilizing Reactjs to efficiently transmit name and value to Material UI autocomplete

I am trying to customize the Material UI Autocomplete component. I need to pass name, value and onchange similarly to how it is done for TextField. Can someone please help me achieve this? My current code is not functioning as expected. < ...

Duplicating labels with JavaScript

I need assistance with copying HTML to my clipboard. The issue I am encountering is that when I try to copy the button inside the tagHolder, it ends up copying <span style="font-family: Arial; font-size: 13.3333px; text-align: center; background-color: ...

Utilize a recursive function to incorporate data into an array nested within other arrays

I am facing an issue where the data I'm trying to add to an element containing nested arrays is not getting updated in MongoDB, even though it appears correctly in the console. I have developed a function to navigate through the entire structure of th ...

Creating markers for every value in a table using Google Maps API v3

Looking for some guidance here. I have a table with multiple values that I need to process using a function. Could someone help me with a suitable loop in jQuery or JavaScript that can achieve this? I'm still learning the ropes of these languages. My ...

Issue encountered with create-next-app during server launch

Encountering an error when attempting to boot immediately after using create-next-app. Opted for typescript with eslint, but still facing issues. Attempted without typescript, updated create-next-app, and reinstalled dependencies - unfortunately, the prob ...

JavaScript and jQuery syntax are essential for web development. Understanding how

I've been searching everywhere but couldn't find syntax similar to this: var mz = jQuery.noConflict(); mz('#zoom01, .cloud-zoom-gallery').CloudZoom(); This basically means: jQuery.noConflict()('#zoom01, .cloud-zoom-gallery') ...

Using Fabric.js to manage image controls situated beneath another overlay image

I'm currently working on a canvas user interface using jquery and the fabric.js library. I managed to add an overlay png image with transparency by implementing the code below: var bgImgSrc = bgImg.attr('src'); canvas.setOverlayImage(bgImgS ...

Receiving JSON in a C# web service: A step-by-step guide

I created a JSON string using jQuery and now I want to send it to a C# web API controller. Here is an example of the JSON object: {"Name":"","Type":"4","Meals":["2","3"],"Excludes":["Beef","Chicken"]} I attempted to send it with a URL structure like thi ...

What is the best method for loading multiple HTML files into a Div container?

Recently, I made the decision to improve the look of an online manual I have been working on for my company by incorporating Bootstrap. The manual is structured with a tree-view that contains titles linking to HTML files with information and CSS stylesheet ...

What is the process for populating dropdown options from state?

I've been struggling to populate a select element with options based on an array in state. Despite trying various methods, the code snippet below seems to be the most detailed (I'm still getting familiar with React after taking a break for a few ...

Is it more efficient to declare a variable or directly return the variable from the Element's getText() promise in Protractor?

I am facing a scenario where I need to retrieve the text of a web element using a promise and then extract a specific part of the string for further processing. Which example, the one at the top or the bottom, should I use? var id = element(by.binding( ...

How to pass property data between sibling components in Vue 2

I am facing a situation with two components - Header.vue and Sidebar.vue In Header.vue, there is a button that when clicked should change the value of a property in Sidebar.vue The template code in Header.vue looks like this: <a v-on:click="toggl ...

How can client-side routing be effectively utilized?

I have a question about the utilization of AngularJS and Node.js in my web application. I have implemented client-side routing using routeProvider to navigate within different pages. All data is retrieved from a RESTful API server-side. However, most of ...

Closing Popover Instance from another Component (Ionic, Typescript)

I've been dealing with an issue where a function that I imported from another class isn't getting called and the parser isn't recognizing it. The Popover in my code also can't be closed. I've tried various similar solutions, but no ...

Using a React PureComponent to pass parameters from a Child component

I am facing an issue with my TodosList component that displays a list of individual Todo components. Below is the code snippet for the Todo component: export class Todo extends React.PureComponent { render() { return ( <li onClick={this.pr ...

Looking for assistance with a JavaScript code snippet

I have encountered an issue while iterating through receipts in the given code snippet. The objective is to fetch the receipt number for each receipt and add it to a JSON object. However, I am facing a problem where the same receipt is appearing in two sep ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

Switching between two states of a single 'td' element within a column

I am trying to implement a feature where only specific elements in the fourth column of a four-column table toggle when clicked. For example, clicking on an element in the fifth row third column should toggle the corresponding element in the fifth row four ...

Launching JQuery modal upon button click

I'm encountering an issue with jQuery Mobile. Here is the JSFiddle link: http://jsfiddle.net/Gc7mR/3/ Initially, I have a Panel containing multiple buttons. The crucial button has an id of 'define'. <div data-role=header data-position= ...

Tips for prohibiting the use of "any" in TypeScript declarations and interfaces

I've set the "noImplicitAny": true, flag in tsconfig.json and "@typescript-eslint/no-explicit-any": 2, for eslint, but they aren't catching instances like type BadInterface { property: any } Is there a way to configure tsco ...