Encountering a problem with TypeScript dictionary

I have created a TypeScript dictionary using the following code:

const skills = x
        .map(y => y.skills)
        .flat(1)
        .map(z => {
          return { [z.id]: { skill: z } };
        });

This is the resulting array from the code above:

{ 7ff2c668-0e86-418a-a962-4958262ee337: {skill: {…}} }
{ c6846331-2e11-45d6-ab8d-306c956332fc: {skill: {…}} }
{ 0fc0cb61-f44d-4fd0-afd1-18506380b55e: {skill: {…}} }
{ 36dc0b74-84ee-4be2-a91c-0a91b4576a21: {skill: {…}} }

The problem I am facing is that I cannot access the dictionary by key:

const id = '7ff2c668-0e86-418a-a962-4958262ee337';
const one = myArr.find(x => x === id); // returns undefined
const two = myArr[id]; // returns undefined

Does anyone have any suggestions on how to resolve this issue?

Answer №1

To retrieve the key of each object within your array, you can utilize the Object.keys() method. In this scenario, the key for each object is its id. You can then use this key to check if it matches with a specific id (in this case, x).

Here's an example to illustrate:

const myArr = [
{"7ff2c668-0e86-418a-a962-4958262ee337": {skill: 1}},
{"c6846331-2e11-45d6-ab8d-306c956332fc": {skill: 2}},
{"0fc0cb61-f44d-4fd0-afd1-18506380b55e": {skill: 3}},
{"36dc0b74-84ee-4be2-a91c-0a91b4576a21": {skill: 4}}],
id = "36dc0b74-84ee-4be2-a91c-0a91b4576a21",
index = myArr.findIndex(x => Object.keys(x)[0] === id); // find the index of the object with the matching key

myArr[index] = {newKey: "newValue"}; // set a new value for the object found at the index
console.log(myArr);

Answer №2

Instead of creating an array of objects, I recommend creating a single object with your ids as keys.

For instance:

const skills = x
    .map(y => y.skills)
    .flat(1)
    .reduce((acc, z) => {
        acc[z.id] = z;
        return acc;
    }, {});

Your myArr will be structured like this:

{
    '7ff2c668-0e86-418a-a962-4958262ee337': {...}
    'c6846331-2e11-45d6-ab8d-306c956332fc': {...},
    '0fc0cb61-f44d-4fd0-afd1-18506380b55e': {...},
    '36dc0b74-84ee-4be2-a91c-0a91b4576a21': {...}
}

You can then access the objects as intended:

const skill = myArr['7ff2c668-0e86-418a-a962-4958262ee337'];

Answer №3

Utilize the power of maps for better efficiency,

Map is a modern data structure introduced in ES6, allowing you to store key-value pairs similar to languages like Java and C#.

let map = new Map();
const skills = x
        .map(y => y.skills)
        .flat(1)
        .map(z => {
          map.set(z.Id,  { skill: z })
          return  map;
        });

//Access entries
map.get("7ff2c668-0e86-418a-a962-4958262ee337");     //40

//Check if entry exists
map.has("7ff2c668-0e86-418a-a962-4958262ee337");       //true

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

Is there any truth to the idea that storing in the session cache can prevent frequent executions of the backend code?

As I work on creating a website using the Zend Framework, I encounter a situation where I am utilizing AJAX to save store ratings in my database. One crucial piece of information required for this process is the key that identifies the specific store for w ...

Unusual characteristics of decision-making

Here is a snippet of my JavaScript code: function getSelectedText(){ if(window.getSelection){ select = window.getSelection().getRangeAt(0); var st_span = select.startContainer.parentNode.getAttribute("id").split("_") ...

Trouble arises when using both jQuery and JPagination as JPagination does not function properly

Having trouble getting JPagination to work with a <div> containing <li> elements. Unsure if it's an ID conflict, PHP-related issue, or something else entirely. Would appreciate any help in figuring out the problem. Here is the setup. The ...

Google Maps API Error: Marker Title Not Found

I am currently developing a map feature that allows users to click on it and generate new markers. These markers should display some information in the sidebar, including latitude, longitude, and a title. The issue I am facing is with the title of the firs ...

Generate a unique JavaScript token using user-specific information

I am in need of a unique identifier for users that can be generated without conflicting with other users' tokens. One idea I had was creating a token using the MD5 hash of navigator.userAgent + new Date().getTime(). However, I don't want to use a ...

Struggling with organizing and summarizing cell information in Excel through VBA

I have made some updates. Here are the main highlights of the update: I modified a part of the code to eliminate unnecessary commas in the resulting Sheet8.L5 field. I incorporated a suggestion proposed by feelththis. The current output now displays "1, ...

Cache for JSON Schema in VS Code

After updating to TypeScript 1.5 (now out of beta), I am eager to utilize the json schema helpers in VS Code. Upon configuring tsconfig.json, I noticed that only commonjs and amd module options are available, while umd and system are missing based on this ...

Unable to attach scope variables in AngularJS

I currently possess the following files: index.html: <!DOCTYPE html> <html> <head> <title>Gestore Anagrafica</title> </head> <body> <div> <h3>Insert new person</h3> <d ...

Upgrade from "typings" to "@types" using [email protected]

My Angular app is currently using 4.1.3 with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c094b9b0a5b3a3b2a9b0b480f2eef0eef3">[email protected]</a>. I've heard that for Typescript versions higher than 2.0, ...

Using HTML to dynamically alter a row's background color depending on its value

I have a table within an HTML page that I would like to color all rows in red when the first column reaches a specific value. After researching on StackOverflow, I found suggestions to add these two attributes (border-collapse and border-spacing) to my ta ...

Struggling to retrieve CSS property from a child element?

Check out this HTML snippet: <div id="ctr" class="faden-slider-container"> <div class="conteneur-image" ></div> <div class="conteneur-image" ></div> <div class="conteneur-image" ></div> </div> ...

The Angular Subject() Observable is not functioning properly in another component

manage-employee.component.ts @ViewChild(DxDataGridComponent) dataGrid: DxDataGridComponent; gridForManageEmployee: any; constructor( private router: Router, private employeeService: EmployeeService ) { this.loadEmployeeData(); } ...

How can I alter the color of the menu text when scrolling to the top of a webpage?

As I navigate my website, I encounter a menu with a transparent background at the top that changes to black as I scroll down. On a specific page where the background is white, this presents an issue: when the menu reaches the top, the white background clas ...

In Typescript, null values are allowed even when the type is set to be non-nullable

Can someone explain why the code below allows for null in typescript, even though number is specified as the type: TS playground // Not sure why null is accepted here when I've specified number as the type const foo = (): number => 1 || null ...

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 ...

What is the best way to restrict the number of iterations in ngFor within Angular HTML

I want to use ngFor to display a maximum of 4 items, but if the data is less than 4, I need to repeat the loop until there are a total of 4 items. Check out this example <img *ngFor="let item of [1,2,3,4]" src="assets/images/no-image.jpg" styl ...

In Laravel, enabling the download of files from a directory within a blade template is made easy

I find myself at a roadblock in the middle and am unable to proceed. I have a folder with files inside, and I want to provide a way for users to download them through a link on a blade view. $fileNameGlob = glob($directory.""*.*"", GLOB_BRACE); ...

The toggle password visibility eye is experiencing an error with an Uncaught ReferenceError: An invalid assignment is being attempted in the code

Here's a code I wrote for toggling password visibility, but I encountered an error: HTML: <!--Hide/Show password--> <button class="form-password__visibility" type="button" onclick="$('#inp ...

Next.js displays component twice

When examining the first image, it appears that Next.js rendered this element twice. Initially, I suspected the issue was related to the tables I used. However, even after removing the tables and replacing them with just , the element still renders twice, ...

Angular: Struggling to iterate through nested arrays within a model

I am facing an issue with transferring data from a table populated using an array received from an API to a modal. The data contains nested arrays, and while I can access these elements in the view, I encounter errors when trying to display them in the mod ...