Having difficulty in converting JSON objects into key/value pairs in Angular 7

I have a task to convert my JSON data from its current format as shown below:

 cacheMapDataDto = [{
    "cacheName": "cache_nchl_individual_type",
    "count": 2,
    "mapObj": {
      "NCHL_BI_BATCH_VERIFICATION": false,
      "NCHL_STL_BATCH_VERIFICATION": false
    },
    "nameOfCache": "NCHL Verification Status"
 }] 

To the desired format specified below:

{"cacheName":"cache_member_dto_type",
"count":1,
"mapOfDto":[{"id":merCode,"value":"1"},{"id":merName,"value":"DE"},{"id":merId,"value":"10"}]
"nameOfCache":"Member DTO"
};

In order to achieve this, I attempted to convert the mapOfDto to key/value pairs using the following method:

formatData(cacheMapDataDto:any){

  console.log("abc");

   console.log(cacheMapDataDto);


  this.result = Object.keys(cacheMapDataDto.mapOfDto).map(function(key) {
    return this.result[key] =cacheMapDataDto.mapOfDto[key], this.result;
  });

  console.log(this.result);

  this.cacheNewData={
  "cacheName":cacheMapDataDto.cacheName,
  "count":cacheMapDataDto.count,
  "mapOfDto":this.result,
  "nameOfCache": cacheMapDataDto.nameOfCache

  };

  console.log(this.cacheNewData);


  }

However, I encountered an error stating:

TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at CacheMetaDataComponent.formatData

The source of the error seems to be in this particular line of code within the TypeScript file:

 this.result = Object.keys(cacheMapDataDto.mapOfDto).map(function(key) {
    return this.result[key] =cacheMapDataDto.mapOfDto[key], this.result;
  });

Do you have any suggestion for a better approach?

Answer №1

Consider this solution based on the revised question:

this.cacheMapDataDto.forEach(cacheMapDataDto => {
      let result = Object.assign(cacheMapDataDto)
      result.mapObj = Object.keys(cacheMapDataDto.mapObj).map(key => ({ key, value: cacheMapDataDto.mapObj[key] }));
})

View Stackbiltz Demo

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

Performing CRUD operations with mongoose and express

My express app is currently being developed with mongoose, and the goal is to integrate it with React for the front end. In my customer controller, I have outlined some CRUD operations, but there are aspects of this approach that I find unsatisfactory. W ...

Why does the selectedItems in the AngularJS grid keep coming back as undefined?

Is there a specific reason why the angularjs grid in my sample isn't displaying the selectedItems properly? Every time I attempt to reference the selectedItems, it returns "undefined." I have tested this in both Chrome and IE with identical outcomes. ...

Having trouble storing radio buttons and checkboxes in MySQL database using AJAX

My app is facing an issue where radio buttons and checkboxes are not correctly entering information into the database. Currently, only text fields are successfully saving data, while checkboxes and radio buttons are only recording the value of the first ra ...

Implementing optional default values in React props using conditional types

I have a dilemma with conditional props types When attempting to set a default value for my optional prop within the conditional type, it causes issues with the types export type ChatBase = { id: string; title: string; } type ChatCardProps = { title: ...

Having a collection of JSON objects, I am unable to remove an element using the pop() method in JavaScript

Hello everyone, I have a collection of JSON objects that are initially set to null in the program like this: var jsonToSaveToDB = [ { ProductID: null, Quantity: null, TotalPrice: null } ]; As the pr ...

Tips for delaying the execution of numerous ajax success callbacks?

In my JavaScript code, I am facing the following situation: call_A(success_A) call_B(success_B) function call_A(success){ // make ajax request success(result) } function call_B(success){ //make ajax request success(result) } function success_A(){ ...

What steps can be taken to convert this function into a more concise, dry function?

I'm attempting to customize a typewriter effect on my webpage, and while it successfully displays predefined data, I am struggling with converting it into a function that can receive values and then display those values. I have made attempts to modif ...

JavaScript is utilized to update HTML content through an Ajax request, but unfortunately, the styling is

Apologies for the unconventional title, I am currently in the process of creating a website. When the page is initially loaded, I call upon two scripts within the 'head' tag to create an attractive dynamic button effect. <script src="https:// ...

Show a roster of individuals by inputting values that will populate the list with their names

I'm attempting to showcase a list of users by taking the value from an input and using it as a parameter in a get() method. After receiving the response from the get() method, I am pushing it into an object and then trying to display this object in th ...

Can a props be retrieved and passed as an argument to a function?

My goal is to retrieve a prop from MapsStateToProps using react-redux's connect and then pass it to a child component. This prop serves as an argument for a function, which in turn returns something that becomes the state of the child component. Alth ...

In this guide, we will explore the process of designing unique styles for ng

What is the proper way to customize CSS for a specific element? &.ng-select-focused { &:not(.ng-select-opened) > .ng-select-container { border-color: $ng-select-highlight; box-shadow: $ng-select-box-shadow; } } The offi ...

What steps can I take to position tsParticles behind all other elements in my NextJS project?

In full disclosure, I am not a web developer, so my setup may be incorrect. Currently, the particles are covering all other elements on the page. I would like them to be positioned behind the rest of the elements and only show as a background. import Imag ...

Utilizing External Libraries in Angular Full Stack Development

Currently, I am delving into the realm of Angular Full stack which incorporates Angular 2. As a newcomer to this technology, I have noticed that the setup and structure between pure Angular 2 and the Full stack can be quite distinct. This has led me to enc ...

Using ng-init to pass a JSON object

I'm attempting to pass a JSON Object to my application using ng-init and the stringify method, but I am encountering an error. Instead of working as expected, I am getting a Lexer error. Lexer Error: Unexpected next character at columns 8-8 [#] in ex ...

Organize object properties based on shared values using JavaScript

Check out the JavaScript code snippet below by visiting this fiddle. var name = ["Ted", "Sarah", "Nancy", "Ted", "Sarah", "Nancy"]; var prodID = [111, 222, 222, 222, 222, 222]; var prodName = ["milk", "juice", "juice", "juice", "juice", "juice ...

Tips for utilizing express in your typescript projects

I'm curious about the transition of definition files from tsd to typings, and now to @types. How can I incorporate @types in a node/express project? What is currently preferred and what's the reason for moving from tsd to typing and finally to @t ...

Changing the colors of multiple buttons in a React Redux form: a step-by-step guide

When using Redux Form Wizard on the second page, I have two buttons that ask for the user's gender - Male or Female. The goal is to make it so that when a user clicks on either button, only that specific button will turn orange from black text. You ...

What could be causing the OnInit lifecycle hook to fail to execute properly?

I'm having trouble with this code. Every time I run it, the console throws a type error saying it can't read property sort. Does anyone have any ideas on how to fix this? import { Component, OnInit, Input } from '@angular/core'; impor ...

Unable to access property within JSON object sent via POST request

I encountered an issue TypeError: Cannot read property &#39;tasks&#39; of undefined While attempting a new POST request on my API, here is the request body I am using: { "name": "example1", "description": "teaching example1", "rules" ...

Puppeteer encounters difficulty when attempting to click on a particular div element within Gmail

I am attempting to click on the three dots in Gmail by following this link: 1 After that, I want to click on the 'mark all as read' option: 2 Clicking on the three dots works without any issues. However, I am encountering difficulty when tryin ...