Creating a collection of nested arrays from a set of object elements

After making an HTTP request, I receive an array of objects in a JSON response. However, although I can index through the first array to select a specific object, I am unable to extract any values from the objects themselves.

The response I get from my request includes multiple objects within an array. My goal is to navigate through the entire array and access the names and values nested within each object at the second level.

{
    "costByServiceList": [
        {
            "EC2 - Other": 0.0774193717,
            "Amazon Elastic Compute Cloud - Compute": 0.5568
        },
        {
            "EC2 - Other": 0.0774193867,
            "Amazon Elastic Compute Cloud - Compute": 0.5568,
            "AWS Cost Explorer": 0.02
        },
        {
            "EC2 - Other": 0.077419386,
            "Amazon Elastic Compute Cloud - Compute": 0.5568
        },
        {
            "EC2 - Other": 0.0774193613,
            "Amazon Elastic Compute Cloud - Compute": 0.5568
        },
        {
            "EC2 - Other": 0.0774194716,
            "Amazon Elastic Compute Cloud - Compute": 0.5568,
            "AWS Cost Explorer": 0.76
        },
        {
            "EC2 - Other": 0.0774620825,
            "Amazon Elastic Compute Cloud - Compute": 0.5568,
            "AWS Cost Explorer": 0.08
        },
        {
            "EC2 - Other": 0.0763515633,
            "Amazon Elastic Compute Cloud - Compute": 0.5568
        }
    ]
}

I thought about converting the array into arrays, but it seems unnecessary for the desired outcome.

Answer №1

The function Object.entries provides key-value pairs of an object in an array consisting of paired arrays.

response.costByServiceList.forEach(service => 
    Object.entries(service).forEach(([key, value]) => console.log(key, value)));

To achieve the desired result:

let newServices = response.costByServiceList.map(service => Object.entries(service));

This will generate JSON data as follows:

[
  [
    ["EC2 - Other", 0.0774193717],
    ["Amazon Elastic Compute Cloud - Compute", 0.5568]
  ]
]

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

Sorting arrays in JavaScript can become tricky when dealing with arrays that contain values from two different arrays

When working with two arrays in JavaScript that are received from PHP, I combine them into a single array. Each element in these arrays contains a created_at value (from Laravel), and I want to sort these elements by their created_at values. The issue ari ...

Barreling is essential for TypeScript custom paths to function properly

This morning has been dedicated to exploring ts-paths in order to shorten my import paths. After some experimentation, I have found that custom paths do work IF you set up barreling (having an index file that exports your modules) root ├── client ...

Is the Angular Karma test failing to update the class properties with the method?

I am struggling to comprehend why my test is not passing. Snapshot of the Class: export class Viewer implements OnChanges { // ... selectedTimePeriod: number; timePeriods = [20, 30, 40]; constructor( /* ... */) { this.selectLa ...

Tips for creating a custom waitForElementText function in Playwright

I need to implement a function called waitForElementText() in playwright. For example, I have headers labeled with the CSS selector '.header-name' on each page. When navigating from the Home page to the Users page, I provide two parameters to ...

Understanding the significance of the add() operator in RxJS

Can someone clarify the purpose of the add() operator in rxjs? I've seen it mentioned that it includes a teardown function, but there isn't much detail on what exactly a teardown is or why it's necessary. My specific query relates to impleme ...

Real-time database functionality in MySQL akin to Firebase's capabilities

Recently, I've been experimenting with Angular4 and Firebase in hopes of finding a solution for a new, challenging project. While I've been able to make it work for simpler tasks, I'm struggling with Firebase's JSON data structure which ...

Mix up the characters in the array to create a new randomized string

My task involves working with a char array of size 12, which can be represented as follows: {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k&a ...

The Angular 2 function within the subscribe method is being triggered before the request has finished processing

I have been attempting to extract a parameter from a URL and then passing it to another method. Below is the code snippet: ngOnInit() { this.getParamValues(); } getParamValues() { this.route.queryParams.subscribe(params => { ...

Angular webpack starter - $ definition

I created a new app using the Angular 2 Starter by AngularClass. When I open the console (in both Chrome and Firebug), I can type: a = $('body') The variable a appears to be an object that looks like a DOM element. However, I am unable to run ...

An issue was encountered in the karma/config.tpl.ts file at line 13, column 18 - a TS1109 error indicating that an expression was expected. This

I'm encountering the following error after updating to Angular 9, so I haven't downgraded TypeScript. Could someone please assist me? I've tried numerous solutions without success. node_modules/karma/config.tpl.ts:66:16 - error TS1005: &apo ...

retrieve a shared string from an array when toggled

Regarding the use of SelectionModel for mat-checkbox, a function is called on each click: toggleSelection(row) { this.selection.toggle(row); console.log("Selection"); console.log("this", this.selection.selected); this.selection.selected.f ...

What are some ways to incorporate advanced/nested type variables when using arrow functions?

Is there a way to use "advanced/nested" type variables, similar to how T is utilized in this function declaration, when working with arrow functions? function wrapInObject<T>(key: string) { return (x: T) => ({ [key]: x }); } I attempted to ach ...

The inner foreach loop will consistently capture the final iteration of the outer foreach loop

Here is a foreach loop with an inner foreach loop that needs some attention: foreach ($options_default as $key=>$value) { foreach ($option_names as $option_name_key=>$option_name_value){ $temp = array($key=>$value); ...

Previewing images with Dropzone through extending file types

Want to display an image preview before uploading using dropzone. Attempting to access the images by calling file.preview but encountering the error "it does not exist on type File." Dropzone extends the file type with a preview?: string. How can I access ...

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...

Tips on handling parameters in the form of a single value or an array of values

I've implemented multiple functions structured like this: this.something = function (which) { // Can be one or many. if (!Array.isArray(which)) { // Single input case. doSomething(which); } else { ...

Exploring The Depths of HOC with Enzyme and TypeScript

I have a higher-order component (HOC) that I need to test. During shallow mounting, I need to call some class methods: it('Should not call dispatch', () => { const dispatch = jest.fn() const WrappedComponent = someHoc(DummyComp ...

The .forEach() method in Javascript is not suitable for DOM nodes as they are subject to change during the iteration

Having an issue with moving all DOM elements from one node to another, I initially used this code: div.childNodes.forEach((n) => me.container.appendChild(n)); However, I noticed that only half of the nodes were being copied. It seems that the problem ...

Issue with Angular ngFor not updating radio button value when ngModel is set

Hello, I am fairly new to working with Angular and could really use some assistance with a problem I've run into. Essentially, I am receiving an array of objects from an API like this: [{name: "abc", score: 2},{name: ""def, score: ...

The Swagger-ui tool condenses objects into query parameters, while the angular client that it generates does not

I'm currently working on a Spring Boot application that includes the following Rest function: @SecuredMaster @GetMapping(path = "/mitarbeiter") @Operation(security = {@SecurityRequirement(name = "jwt")}) public Page<MitarbeiterListRow> getMitar ...