Combining two arrays in typescript using the map method

I have an array of heart rate, height, and weight values.

{
    "heart_rate": 27,
    "height": 82,
    "weight": 78
}

There is also a second array containing information about each value, such as ID, label, and description.

[
    {
    "id": "heart_rate",
    "description": "le ratio coeur",
    "label":"ratio coeur"
    },
    {
        "id": "height",
        "label": "taille",
        "description": "la taille"
    },
    {
        "id": "weight",
        "label": "poids",
        "description": "le poids"
    }
]

My question is, can I use the map function to match the key of the first array with the ID of the second array in order to create a new result array like this?

[
{
 "label": "poids",
 "value": 82,
 "description": "le poids"
},
{
 "label": "taille",
 "value": 78,
 "description": "la taille"
},
{
 "label": "ratio coeur",
 "value": 27,
 "description": "le ratio coeur"
},
]

Answer №1

MGX is spot on. Your initial item does not constitute an array but rather an object.

Here's what you need to do to make it compatible with an object.

const valueObject = {
    "heart_rate": 27,
    "height": 82,
    "weight":78
};

const array = [
    {
        "id": "heart_rate",
        "description": "le ratio coeur",
        "label":"ratio coeur"
    },
    {
        "id": "height",
        "label": "taille",
        "description": "la taille"
    },
    {
        "id": "weight",
        "label": "poids",
        "description": "le poids"
    }
]

const keys = Object.keys(valueObject);
const values = Object.values(valueObject);

const result = array.map((item) => { 
  return {
    label: item.label,
    value: values[keys.findIndex(key => key === item.id)],
    description: item.description,
  };
});

Alternatively, you can transform your valueObject into a Map for a more straightforward solution:

const map = new Map(Object.entries(valueObject));

const result = array.map((item) => { 
  return {
    label: item.label,
    value: map.get(item.id),
    description: item.description,
  };
});

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 is the best way to utilize TypeScript module augmentation with material-ui components?

I have gone through the answers provided in this source and also here in this link, but it appears that they are outdated. I attempted to enhance the type definition for the button component in various ways, including a separate typings file (.d.ts) as we ...

Oops! An unhandled promise error occurred when trying to fetch a URL with a status of 0. The response received has a status code of

I keep encountering an error whenever I try to hit a post request URL: Error: Uncaught (in promise): Response with status: 0 for URL: null at c (http://localhost:8100/build/polyfills.js:3:19752) at c (http://localhost:8100/build/polyfills.js:3:1 ...

Need help with Swift? Want to learn how to incorporate multiple items into a JSON array?

Currently, I am in the process of developing a simple to-do application for the command-line using Swift. The issue I am facing is that when I try to add a new item to the to-do array, it ends up overwriting the existing entry instead of creating a new one ...

What is the best way to retrieve the height and width of a device's display in Angular 2 using Typescript

I came across this code snippet. Do you think it's valid? import {Component} from '@angular/core'; import {Platform} from 'ionic-angular'; @Component({...}) export MyApp { constructor(platform: Platform) { platform.ready().then ...

Encountering an issue: a function is required to return a value if its declared type is not 'undefined', 'void', or 'any'

I have a specific function type that is capable of returning either void or Promise<void: export type CommandHandler = (values: CommandValues) => void | Promise<void>; Currently, I am attempting to utilize this function type in a void function ...

Proper utilization of react-hook-form in conjunction with TypeScript and material-ui to display error messages efficiently

Currently, I am using a combination of react-hook-form with typescript and material-ui. My goal is to pass the error message as a helperText to the TextField. I attempted to achieve this by utilizing helperText={errors.email?.message} however, TypeScript ...

Creating an image array in VB.NET using project resources

I am trying to create an array of images using references to the resources folder, but my current code is not working as expected. Dim imgPictures(8) As Image imgPictures(0) = Image.FromFile(My.Resources.cat_1.ToString) Could someone please guide me on h ...

Guide for retrieving a user object from an HTTP request

I am looking to retrieve only the user object from the request. public async getUserByHash(hash: IHash) { this.logger.log('Hash for check email accessed'); const user = await this.hashRepository.findOne({ select: ['id', ...

Interested in embedding DocuSign within an Angular application using an iframe?

Welcome to a brand new image opportunity! https://i.sstatic.net/Cj05w.png I am looking to integrate Docusign for users to sign PDF documents. The plan is to embed it in an iFrame. Currently, the backend is developed using .NET Core and the frontend use ...

Problem with rendering Ionic v2 HTML in Angular 2

Issue at Hand: Currently, I am developing a hybrid app using Ionic v2 and everything seems to be functioning correctly. When I use ionic serve, the app works as expected in the browser with no issues. However, when I try running the app on an Android devi ...

Utilizing Material-UI with MobileDialog HOC in TypeScript: A Beginner's Guide

I'm running into an issue while trying to implement withMobileDialog in my TypeScript code. Below is the snippet of my code, inspired by a code example from the official documentation. import withMobileDialog, { InjectedProps } from "@material-ui/co ...

Unable to transform the singular JSON object received from the server into the necessary format in order to analyze the data

Forgive me if my questions seem simple, as I am new to working with Angular. I'm having trouble understanding how to handle a JSON object received from the server and convert it into a custom datatype to use for rendering HTML using ngFor. I've ...

Stop receiving notifications for channel events in Stream with the GetStream.io Chat API

I'm having trouble understanding how to stop listening for channel events in JavaScript using the Stream Chat API. According to the documentation: // remove the handler for all "message.new" events on the channel channel.off("message.new", myChanne ...

What is the best way to populate an array when I'm uncertain about the type of items it will

When I am given an instance of a class that implements an interface, the exact type may not be known. To create an array of this class, regardless of its specific type, I can use the following approach: IWhatever[] ArrayOfClass = (IWhatever[])Array.Create ...

The struggle of implementing useReducer and Context in TypeScript: A type error saga

Currently attempting to implement Auth using useReducer and Context in a React application, but encountering a type error with the following code snippet: <UserDispatchContext.Provider value={dispatch}> The error message reads as follows: Type &apos ...

Managing sessions within a Spring OAuth2 client acting as a gateway for secure communication

While developing a microservices application, I encountered an authentication issue that was addressed in a similar way to @ch4mp's suggestion in their tutorial on . In my case, the oauth2Client serves as both an authentication gateway and a gateway, ...

Having trouble calling a method from one component to another using its instance

Trying to call a method from one component to another is causing some issues. I have created an instance of the component and tried calling its method, but it doesn't seem to be working as expected. In the code snippet below, you can see that I am try ...

Running multiple versions of the Angular CLI on one machine

In my various Angular2 projects, I am faced with the challenge of working with different versions of angular-cli. This means that in order to run and compile each project for production, I need to ensure that the correct version of angular-cli is being use ...

Right-align the text in the title of the material card

Why isn't the CSS aligning my title of matcard to the right? <mat-card [ngStyle]="{ 'margin':'5px','height':'130px'}"> <mat-card-header> <mat-card-title [ngStyle]="{ 'text-align': ...

developing an email feature within Angular, incorporating confirmation emails

I am currently working on implementing a function in Angular to validate email addresses and confirmation emails. However, I am facing an issue where even after correcting the confirmation email to match the original email, I still receive an error message ...