Keys are slipping away in Angular/Typescript when transforming objects into arrays

I'm encountering an issue where my code is returning an object that gets converted to an array, but during this process, the original descriptive keys like url, id, and name are lost and replaced with numerical indices (0, 1, 2, etc.).

How can I maintain these descriptive keys in the final array output? My desired array structure should resemble the following:

[
  "description": "blah blah blah"
  "telephone": "101",
  "id": "bedfordshire",
  "name": "Bedfordshire Police"
]

.ts code:

  fetchForceDetail(){
    return this.http
    .get<ForceDetail[]>('https://data.police.uk/api/forces/' + bedfordshire)
    .pipe(map(responseData => {
      const detailArray = [];
      for (const key in responseData) {
      if (responseData.hasOwnProperty(key))
        detailArray.push(responseData[key])
      }
      return detailArray;
    }))
    .subscribe(forcedetails => {
      console.log(forcedetails);
  });
}

Answer №1

One way to transform an object into an array is by using the Object.keys and Object.values methods.

const exampleObj = {
  color: "blue",
  size: "medium",
  quantity: 10,
}

const objKeys = Object.keys(exampleObj); // ['color', 'size', 'quantity']

const objValues = Object.values(exampleObj); //['blue', 'medium', 10]

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

What Could Be Causing jQplot to Appear Blank?

As a beginner in jQuery and jQplot, I am facing an issue with plotting an array of points onto a graph in my web application. The graph is just showing up blank and I can't seem to pinpoint where the problem lies... The code responsible for executing ...

Tips for using the in_array function in PHP to check array values

I have a question. How can I use PHP's in_array method to check if a new value is present in an existing array that contains JSON data? Below is the code I am working with: {"introId":"582aa53755f5ab487614ddc9","introLabelName":"Age","isIntro":"Yes"} ...

Is there a way to retrieve data from Angular RC4 routing?

Within the app routes: { path: 'calculator', component: CalculatorComponent, data: {physical: Physical}}, In the settings component: if(this.selectedPhysical) { this.router.navigate(['/calculator', this.selectedPhysical ]); } ...

Unlock hidden Google secrets within your Angular application using Google Secret Manager

Can the Google Secret Manager API be accessed with a simple API call using an API key? https://secretmanager.googleapis.com/v1/projects/*/secrets/*?key=mykey returns a 401 unauthenticated error. While the Node.js server powering the Angular app uses the c ...

How can I integrate the "FETCH FIRST n ROWS ONLY" feature into my Kysely DB query builder?

For my projects that are based on TypeScript, Prisma is my go-to DB toolkit. However, I recently encountered a project where Kysely, a type-safe DB query builder, was being used. I'm currently trying to create a query with Kysely that can handle keys ...

What is the process of inserting elements into a nested list?

Just starting out with Python and looking for help. I have a list within a list and I need to add an element to the end of each sub-list. a = [ [0, 1 ,-1, 2, -2, 3, -3, 4, -4, -5, 5, 8], [0, 6 ,-6, 7, -7, 8, -8, 9, -9, -10, 10, 9] ] for i in a: b = ...

Should compile time errors be triggered by generic function constraints?

Surprisingly, the following code does not throw a compile time error as expected. interface Service { } abstract class TestService implements Service { } class TestServiceImpl extends TestService { } class Blah { } function getService<T extends S ...

Is there a way to retrieve an array in Protractor using By.Repeater instead of a string?

I'm currently using the ng-repeat directive and looking to utilize the Protractor repeater in order to retrieve an array: <div ng-repeat="product in landingPage.products" class="landing-buttons"> <a ui-sref="personalInfo"> <but ...

Alter the font color of the text within a specific row of a designated table

Trying to adjust the font color of a specific row within a table using ngClass but encountering issues. This is what I'm attempting: [ngClass]="{'total':item.key === 'Total'}" In the CSS, I have defined: .total { background ...

Having trouble with JavaScript concat function not behaving as it should? Can you provide more details to

I am trying to extract all the cities from an object that contains country names as keys and arrays of cities as values. However, my approach seems to be failing and I can't figure out why. var cities = { "United Kingdom": ['london'], ...

Tips for managing a session when adding a List of strings

((List<string>)Session["answera"]).Add(xle.InnerText); I am encountering an issue while trying to execute this operation, it keeps showing "Object reference not set to an instance of...." I prefer not to use List<string> ast = new List<s ...

What steps do I need to take in order to transfer these codes from AngularJS to Angular?

I am currently working with the code snippet below: var secClassesToCreate = _this.$filter('filter')(_this.selectedSecurityClasses, {operation: 'CREATE'}); var selectedSecClasses = _this.$filter('filter')(_this ...

Touched the Force of ngModel

I am looking to make the required fields show in red in the angular material when the "Submit" button is clicked. To achieve this, I need to trigger the input to be marked as touched. <div class="formRow"> ...

What exactly are Discriminating Unions in the realm of Function Types?

I am struggling to differentiate between members of a discriminated union made up of function types. Take a look at the following example: type _NumFunc = (n: number) => string; type _StrFunc = (s: string) => string; interface NumFunc extends _NumFun ...

dynamically populating a blank cell

Consider a scenario where we have a structure 'v' containing objects with a variable number of elements: >> v(1).a = 1:10; >> v(2).a = 1:20; >> v(3).a = 1:30; To convert this structure into a cell array, we can easily concaten ...

Retrieve data from jQuery and send it to PHP multiple times

<input type="checkbox" value="<?= $servicii_content[$j]['title'] ?>" name="check_list" id="check" /> By using jQuery, I am able to extract multiple values from the table above once the checkboxes are checked. Here's how: var te ...

Is there a way to retrieve a child's parents within an array.filter() callback function even if they were initially filtered out?

Today I stumbled upon the array.filter() method and its accompanying callback function. I have a collection of objects structured like this: var treeAry = [ {"id" : "200", "parent": "#", "type" : "1"}, {"id" : "300", "parent": "#", "type" : " ...

How can I achieve a partial match for an object property in a JavaScript loop

How can I reformat this array of objects const arr = [{ my_first_name_1: { value: 'jane' }, my_last_name_1: { value: 'anderson' } }, { my_first_name_2: { value: 'alex' }, my_last_name_2: { value ...

Utilize a single variable for multiple PHP functions

<?php require_once 'config.php'; // This script includes two functions - one for saving invoice data and another for retrieving invoices. We will focus on the second function that fetches the data without using the $warehouse variable passed ...

Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly. Here is my current logic: Data structure for Products, product = { ...