What is the best way to access the values associated with the keys in an array of objects?

I have an array of objects that has the following structure:

import icon1 from '!!raw-loader!../../../icon1.svg';
import icon2 from '!!raw-loader!../../../icon2.svg';
import icon3 from '!!raw-loader!../../../icon3.svg';
import icon4 from '!!raw-loader!../../../icon4.svg';
import icon5 from '!!raw-loader!../../../icon5.svg';

export const CustomIcons = [
  {
    home: 'icon1',
    homeIcon: (icon)
  },
  {
    series: 'icon2',
    seriesIcon: (icon2)
  },
  {
    explorer: 'icon3',
    explorerIcon: (icon3)
  },
  ...
];

Within the module's constructor, I aim to utilize the values in this way:

export class IconRegistryModule {
  constructor(iconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
    CustomIcons.forEach(icon => {
      iconRegistry.addSvgIconLiteral(Object.keys(icon)[0], sanitizer.bypassSecurityTrustHtml(Object.keys(icon)[1]));
    });
  }
}

Therefore, the addSvgIconLiteral method should be implemented as follows for the initial iteration of the forEach loop:

iconRegistry.addSvgIconLiteral('the value of the key home', sanitizer.bypassSecurityTrustHtml('the value of the key homeIcon');

Answer №1

Here's a useful tip for retrieving object keys from an array.

CustomIcons.map((item) => {
console.log(Object.keys(item));
});

Answer №2

Object.keys(icon)[0] simply retrieves the key. You can then use this key as an index on the icon object.

To obtain the value, you can use icon[Object.keys(icon)[0]].

(It's important to ensure that the first property always contains the URL. It might be beneficial to establish a structure based on an interface with consistent naming as recommended in the comments.)

Edit:
When using an interface, the approach would resemble the following:

export interface CustomIcon {
  name: string;
  icon: string;
}

export const CustomIcons: CustomIcon[] = [
  {
    name: 'icon1',
    icon: (icon1)
  },
  {
    name: 'icon2',
    icon: (icon2)
  },
  ...
]

Subsequently, in the constructor (Object.keys is no longer necessary):

constructor(iconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
  CustomIcons.forEach(icon => {
    iconRegistry.addSvgIconLiteral(icon.name, sanitizer.bypassSecurityTrustHtml(icon.icon));
  });
}

Answer №3

Utilize Object.keys to extract the data from every individual object

let keys = Object.keys(CustomIcons[i])

Next, proceed to cycle through each item in the array using a for loop.

After each iteration, add these items to a distinct 'key array' towards the conclusion of the loop.

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

Utilizing interpolation for a CSS class defined in an external file within Angular 2

Is it feasible to send a variable to a CSS class in an external CSS file within Angular 2, such as: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', sty ...

Choosing a specific element within another element of the same type using JQuery

I've created a complex nested HTML structure shown below: <ul class="root"> <li>Foo 1 <label class="bar-class">bar</label> <ul> <li>Foo 2 <label class="bar-class">bar</label> ...

Collaborative JavaScript repository within the Websphere Liberty platform

Is it possible to utilize a JavaScript library (such as Dojo, JQuery, or other custom developed libraries) as shared libraries within a Websphere Liberty server? For instance, I am interested in storing the .js files in either C:\wlp\usr\sh ...

Guide on managing AngularJS / JavaScript dropdowns with Python and Selenium webdriver

I am looking to automate various browser tasks using Python and the Selenium WebDriver on the Chromium browser. My Python script is currently capable of logging in, navigating to a subpage, performing clicks, and entering information into a form. However, ...

jQuery Datatables causing hyperlinks to malfunction on webpage

After implementing jQuery datatables on this example using a PHP serverside processing file pulling data from MySQL, the Sign-in button used to work but now it just reloads the same index page. Manually typing in the address linked to the Sign In page work ...

It is not possible to transfer information to a JSON document using node.js filesystem and browserify

In an attempt to convert incoming input data from a form into JSON format for storage without a backend, I am exploring the use of Node.JS module "fs" or "file-system". To make this work in a browser environment, I am using Browserify for bundling as it r ...

React: The error message is saying that it cannot retrieve the 'handler' property because it is either undefined or null

I'm having some trouble with event handlers in my React.js project. Every time I try to create an event handler outside of the render function, I end up with an error. Can anyone help me figure out what I'm doing wrong? class CheckboxHandler ext ...

Having trouble loading CSS and JavaScript files in CodeIgniter version 3.0.4?

I am facing an issue with loading my CSS and JS files in the view file. I have already added them to the folder and set the base URL. These codes were working fine with a project I previously did on an older version of CodeIgniter. What could be causing ...

Item removed from the cache despite deletion error

Currently, I am utilizing Angular 8 along with @ngrx/data for handling my entities. An issue arises when a delete operation fails (resulting in a server response of 500), as the entity is being removed from the ngrx client-side cache even though it was not ...

adjust variable increment in JavaScript

As I work on developing a Wordpress theme, I have encountered an issue with incrementing a load more button using Javascript. This is my first time facing this problem with a javascript variable, as I don't always use Wordpress. The variable pull_page ...

JavaScript TweenJS is a powerful library that simplifies

Hey there, it's my first time posting on Stackoverflow. I'm facing an issue with a tween in my code. It seems like the brute function is being called at the end, indicating that the tween should be running. However, I'm not seeing any actual ...

Seeking a quick conversion method for transforming x or x[] into x[] in a single line of code

Is there a concise TypeScript one-liner that can replace the arrayOrMemberToArray function below? function arrayOrMemberToArray<T>(input: T | T[]): T[] { if(Arrary.isArray(input)) return input return [input] } Trying to cram this logic into a te ...

What is causing the check box in the simple_form view to consistently return a value of 1 when checked or unchecked in rails 3.2?

A checkbox with the name "need_delivery" is used to determine whether the next two text boxes should be displayed. These two text boxes are enclosed within a div with the id of task_request_delivery. Below is the code snippet in the simple_form view named ...

How to correctly consume APIs in Ngxs?

In my API calls, I want to have 3 actions: GetItem, GetItemFailed, GetItemSuccess. Although I am not very familiar with rxjs operators, I currently only use the subscribe method for handling api calls. Here is an example of what I have: @Action(GetItem) ...

Is resizing possible using the Canvas identifier?

Is it possible to adjust the canvas size to match the width of the page using the canvas id's style in the html? Then in your javascript code for the canvas, can you have resize listeners that are responsive to the canvas size at any given time? I c ...

Issues with Ionic's $state.go and ui-sref functions not functioning as expected in the app

While attempting to change the view on the Ionic View app for iOS (I have not tested on the Android app), I encountered a bug that seems to have a solution, but unfortunately, it does not work for me. Bug info: Bug info 2: My Ionic information is as fol ...

Different ways to separate an axios call into a distinct method with vuex and typescript

I have been working on organizing my code in Vuex actions to improve readability and efficiency. Specifically, I want to extract the axios call into its own method, but I haven't been successful so far. Below is a snippet of my code: async updateProf ...

Creating Class Names Dynamically in Angular 2 Using ngFor Index

Encountering an issue while trying to generate a dynamic class name based on the ngFor loop index in Angular 2. Due to restrictions, I had to use a specific syntax as Angular 2 does not support ngFor and ngIf together on the same element. Given this setup ...

Is there a way to generate a checkerboard dynamically with the help of jQuery?

I've made some progress so far, but I'm facing a challenge where I need to push 8 <td> elements into 8 different <tr> elements without hardcoding anything or modifying the HTML directly. Any help would be appreciated! JavaScript v ...

What is the correct way to integrate knex using inversify?

Is there a way for me to set up knex and utilize the Inversify dependency injector to inject it wherever it is required? ...