Looping through a detailed JSON array filled with objects to extract just a pair of items is essential. I aim to achieve this efficiently by utilizing LOD

Looking at this intricate JSON object...

Here's a snippet of the code:

    entity: [{entityName: "Nrm", page: 0, pageSize: 241, status: "successfully perfrom: select Operation",…}]
    0: {entityName: "Nrm", page: 0, pageSize: 241, status: "successfully perfrom: select Operation",…}
    entityName: "Nrm"
    page: 0
    pageSize: 241
    rows: [{columns: [{paramName: "country_alpha3_code", paramValue: "PLW", dataType: "String"},…]},…]
    [0 … 99]
    0: {columns: [{paramName: "country_alpha3_code", paramValue: "PLW", dataType: "String"},…]}
    columns: [{paramName: "country_alpha3_code", paramValue: "PLW", dataType: "String"},…]
    0: {paramName: "country_alpha3_code", paramValue: "PLW", dataType: "String"}
    dataType: "String"
    paramName: "country_alpha3_code"
    paramValue: "PLW"
    1: {paramName: "country_name", paramValue: "PALAU", dataType: "String"}
    dataType: "String"
    paramName: "country_name"
    paramValue: "PALAU"
    2: {paramName: "country_alpha2_code", paramValue: "PW", dataType: "String"}
    dataType: "String"
    paramName: "country_alpha2_code"
    paramValue: "PW"

Here's a visual representation with a script snippet:

https://i.sstatic.net/f0o41.png

The objective is to create a simple JSON Object for a country Drop Down without the need for a custom API, using Typescript and Lodash

countries = {
  [{
      name: "United States",
      code: "US"
  },{
      name: "Canada",
      code: "CN"
  },{
      name: "Italy",
      code: "IT"
  },
  ....]

}

That's the concept.

Following is my typescript function where I intend to generate the new JSON Object

async getCountryOptions() {
  // this.services.getCountries();
  const response = await this.services.getCountries();

  // console.log('RESPONSE AFTER AWAIT: ', response);
  
  this.countries = this.services.countryList;

  console.log('Did we get countries: ', this.countries);

  // Now to create a new array for only country code and name
  ****************** HERE *********************


  // I TRIED THIS but I got ...val is not an iterator
  this.newJSONCountryArr = Object.entries(this.countries)
    .map(([key, val]) => [...val, key]);
  console.log('Result: ', this.newJSONCountryArr);

  if (this.countries) {
    this.meta.countryOptions.push(this.services.countryList);
  } else {
    console.log('Whoops! ')
  }
}

Answer №1

Find the answer in the latest UPDATE section

// To create a fresh array containing only country code and name
// ************* HERE IS THE RESOLUTION **************
var results =_.map(this.countries, function(res) { 1
  console.log('result: ', { country_name: res.columns[1].paramValue, country_alpha2_code: res.columns[2].paramValue });
  return { country_name: res.columns[1].paramValue, country_alpha2_code: res.columns[2].paramValue }; 
});

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

Tips for simulating difficult private attributes within a class during unit testing in TypeScript

Is there a way to mock the value of a hard private property in a unit test? For example, how can I expect something like expect(event.getEventHis()).toBeEqual(['a', 'b']) export class EventController { #event: []; constructor() { ...

The Art of Dynamic Component Manipulation in Angular

The current official documentation only demonstrates how to dynamically alter components within an <ng-template> tag. https://angular.io/guide/dynamic-component-loader My goal is to have 3 components: header, section, and footer with the following s ...

What is preventing React CLI from installing the template as TypeScript?

When I run npm init react-app new-app --template typescript, it only generates a Javascript template project instead of a Typescript one. How can I create a Typescript project using the CLI? Current Node JS version: 15.9.0 NPM version: 7.0.15 ...

How can one define a getter within an interface?

One of my classes is structured like this (only showing a portion here): export class LinkedListNode<t> extends windward.WrObject implements ILinkedListNode<t> { public get next(): LinkedListNode<t> { return this._next === thi ...

When a reaction function is triggered within a context, it will output four logs to the console and

My pokemon API application is encountering some issues. Firstly, when I attempt to fetch a pokemon, it continuously adds an infinite number of the same pokemon with just one request. Secondly, if I try to input something again, the application freezes enti ...

What is the process for testing an iframe and retrieving all of the response headers?

I'm currently working on a web application that can display URLs in an iframe. However, I also want to be able to test the URL before showing it in the iframe. The goal is to wait for a response and only display the iframe if there are no errors or if ...

styled components are having issues with background gradients and opacity not functioning properly

Hello, I am currently working with styled components and have the following global style code: const GlobalStyle = createGlobalStyle` html{ font-family: roboto; background: linear-gradient(45deg,rgba(137,255,255,0.5),rgba(161,252,143, 0 ...

ERROR: Unhandled promise rejection: Route cannot be found. URL Segment: 'details'

My current setup involves a router configuration in my Angular application. Below is the code snippet showcasing my router settings: import { Route, RouterModule } from '@angular/router'; import { ProjectDetailsComponent } from '../componen ...

Troubleshooting the Issue with Angular Material Dialog Imports

Hey there, I'm trying to utilize the Angular Material dialog, but I'm encountering issues with the imports and I can't seem to figure out what's wrong. I have an Angular Material module where I imported MatDialog, and I made sure to i ...

I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website : https://i.sstatic.net/myJAf.png On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Ri ...

Methods for resolving a ViewStyle typescript issue in react native

Trying to pass a width parameter into StyleSheet is causing an error like this: <View style={styles.children(width)}>{children}</View> Here's how I'm trying to use it: const styles = StyleSheet.create({ modalContent: { flex: ...

Navigating dropdown list items using the keyboard in TypeScript is a breeze

I've encountered a bug while working on my open-source project. The issue is with navigating the dropdown list items using the keyboard (arrow key/tab). I have implemented the keyboard-navigation logic, but I'm unsure of how to make it work corre ...

What causes the typescript error in my code: The argument being passed is either a string, an array of FilterData, an array of numbers, or an array of Moments, which is not compatible with a parameter of type 'string'?

When writing my code, I have the need to utilize various types for different scenarios. Depending on the situation, the type may be a string, number[], FilterData[] (a custom type), or Moment[]. To address this requirement, I defined the type as: export ty ...

Unable to transmit props while employing Typescript in ReactJS

Attempting to pass props from components like AllProducts, MenProducts, etc. to the AddToCartButton component for reusability presents a challenge. When trying to pass props using: <AddToCartButton id={product.id} /> An error is encountered: Type & ...

Nestjs RabbitMq Microservices

I'm currently developing a microservice that is responsible for receiving messages from RabbitMQ. However, I am encountering an error message as follows: ERROR [Server] There is no matching event handler defined in the remote service. Event pattern: u ...

Modifying the version target of TypeScript code results in the TypeScript Compiler being unable to locate the module

After installing signalr via npm in Visual Studio 2019, I encountered an issue. When the target in my compiler options is set to ES6, I receive the error TS2307 (TS) Cannot find module '@microsoft/signalr.'. However, when I change the target to E ...

After deploying to Heroku, cal-heatmap encounters errors despite functioning correctly in a local environment

I successfully implemented a cal-heatmap instance in my Angular 2 (angular-cli) project locally, but when I deployed the project to Heroku, I encountered some errors that prevent the cal-heatmap from displaying. https://i.stack.imgur.com/8gY90.png The er ...

Angular unable to send object to HTML page

Struggling with learning angular, encountering new challenges when working with objects in different components. In two separate instances, try to implement two different mechanisms (microservice or service component serving an object directly). This speci ...

Utilizing Express JS to Optimize JPEG File Loading with Cache Headers

I have been working on implementing Cache-Control for my static image files. I have successfully set this header for HTML and JS files: https://i.stack.imgur.com/9VuWl.png However, I am facing challenges with JPEG files: https://i.stack.imgur.com/p52jm. ...

Is there a way to drop a pin on the Google Maps app?

Is there a way to pinpoint the specific location on Google Maps? <google-map id="map-container" width="100%" height="100%" class="maps"></google-map> ...