build a key-value pair collection in Angular 2

Struggling to figure out how to create an associative array in Angular2?

I've attempted the following:

  onSubmit(){

let inputfield:any[]  = [];

for(var i=0; i<this.inspectionform.value["inputfileds"].length; i++){

 if(this.inspectionform.value["inputfileds"][i]["input"] != ""){
    //need help here
    inputfield.push( i : this.inspectionform.value["inputfileds"][i]["input"]) //syntax error returned
  }

}

} What I actually want is to add a key and value pair to the array

Something like

1:sdbhd //add this to the array

In my attempts within the for loop, I've tried:

//inside the for loop

     let arrayval = [];
    arrayval.push(this.inspectionform.value["inputfileds"][i]["input"])
    arrayval.push(i)

    inputfield.push(arrayval);

This results in a new object of this type being created each time:

0:njnf
1:1(value of i)

Answer №1

If you're deciding between using a Map or a plain object, I recommend opting for a plain object;

Example

const myobject = {}
myobject.foo = 1
myobject.foo === myobject['foo'] // true
myobject['bar'] = 1337;
myobject.bar === 1337 // true
myobject.foo-bar = 1 // ERROR: cannot have dashes
myobject['foo-bar'] = 1 // Works

In ES6 and newer browsers, you can easily retrieve all keys by using Object.keys(myobject). For older environments, looping over keys using for ... in is necessary and can be seen in this polyfill: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Another consideration to keep in mind is ensuring that each item in the property chain is defined. For instance, if you have

var foobar = {
  foo: { bar: 1 }
}

you can successfully call foobar.foo.bar.toString() to get "1", but attempting foobar.foo.bang.toString() will result in an error since bang is not defined on the foo object.

To handle this, add a guard check like

foobar.foo.bang && foobar.foo.bang.toString()
, which only executes the toString method if bang exists.

An easier approach is utilizing lodash, providing functions like _.get and _.set that manage guards and create missing properties for you.

Answer №2

When working with Javascript, it's important to note that there is no associated array feature. Instead, you can simply use {} or utilize the new Map API.

let exampleMap = new Map();

exampleMap.set('key1', 'value 1');

exampleMap.set('key2', 5);

console.log(exampleMap.get('key1'));

To dive deeper into this topic, check out: Map in Javascript

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

Embedding an image by inserting the URL

I have been attempting to implement functionality in Typescript where an image preview appears after a user enters a URL, but I have only been successful in achieving this in JavaScript. My goal is to display a preview of the image and enable the user to u ...

Tips for determining if an HTMLElement has already been created

One issue I'm facing is with a third party component that emits an "onCellEdit" event and passes a cell element as a parameter. My goal is to automatically select the entire text in the input element generated inside this cell when the event occurs. ...

Adding an anchor tag to an ngx-datatable-column can be done by utilizing the properties

My task involves loading data from the server and populating the ngx-datatable. When a specific column is clicked (with either a link <a href="randomurl"/> or [routerLink]="randomcomponent"), it should redirect to a different page or display a modal ...

Optimizing Angular6 Pipe Filter Performance for Large Arrays

I have written a filter that retrieves a subset of items from a large array consisting of around 500 items. import { Injectable, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchFilter' }) @Inject ...

What is the most reliable method for converting a 32-bit unsigned integer to a big endian byte array?

Looking for a simple and reliable method to convert an unsigned integer into a four-byte-array in big endian format, with padding if necessary? Take a look at this example: Input value: 714 Output: Resulting byte array [ 0xca, 0x02, 0x00, 0x00 ]; By the ...

Tips for transferring TimeZone Name from Angular to .NET API

Currently, the API I am working with accepts TimeZone names (such as America/Denver) as a string. In my Angular UI application, I automatically pass the browser timeZoneName to the API. However, when the API receives the string America/Denver, it interpret ...

I have been encountering an error consistently whenever I attempt to access the _id parameter in my angular front-end

EmployeeComponent.html: 11 ERROR TypeError: Cannot read property '_id' of undefined This is the error I encounter whenever I attempt to access the id in my front-end implementation using Angular. I have attempted incorporating ngIf, but unfo ...

Mocking store.dispatch in Jest with TypeScript did not result in any function calls being made

Testing Troubles I'm a beginner in the world of testing and I'm facing some challenges. Despite going through all the documentation on jest, I couldn't find information specific to TypeScript cases. Currently, I'm on a quest to figure ...

Challenges with importing and using jspdf and autotable-jspdf in Angular 8

Issue with Generating PDF Using Angular 8, JSPDF, and JSPDF-AutoTable I am facing a challenge with exporting/generating a PDF based on an HTML grid. I need to make some DOM changes with CSS, remove toggle buttons, alter the header, etc. However, all the s ...

How to access an array mapped to a specific key within an object in JavaScript

Is there a way to access an array mapped to a specific key in a JavaScript object? data = {}; data.key = 'example'; data.value = 'test'; data.list = [111, 222, 333]; Viewing the list of items works fine: alert(data.list); // displays ...

The challenge of deallocating a dynamic array of C++ class pointers

#include <stdio.h> #include <stdlib.h> #include <windows.h> #define ROW 1 class Foo { public: Foo() { this->dummy = new unsigned int[100]; } ~Foo() { delete[] this->dummy; this->dummy ...

Extract pieces from a union type that includes a discriminator which is itself a union

My current type declaration looks like this: enum Type { A = 'A', B = 'B', C = 'C' } type Union = | { type: Type.A | Type.B; key1: string } | { t ...

Steps for converting TypeScript code to JavaScript using jQuery, without the need for extra libraries or frameworks like NPM

My single-page dashboard is quite basic, as it just displays weather updates and subway alerts. I usually refresh it on my local machine, and the structure looked like this: project/ index.html jquery-3.3.1.min.js script.js I decided to switch it t ...

How can I display the value of a radio button that has been chosen?

Would you mind sharing how to display the selected value of a radio button? I attempted it this way, but unfortunately, it did not work. You can view my code at this link. <mat-radio-group [(ngModel)]="favoriteName"> <mat-radio-button *ngFor="l ...

ReactJS Typescript Material UI Modular Dialog Component

Hello, I need help with creating a Reusable Material UI Modal Dialog component. It's supposed to show up whenever I click the button on any component, but for some reason, it's not displaying. Here's the code snippet: *********************TH ...

React Material UI - All radio buttons within a list can be individually selected

I'm looking to create a set of Radio Buttons for each element in my array. While my project is functioning well overall, I'm having issues with the radio buttons as they are all selectable at once. ...

"Unindexing data in Angular: A step-by-step guide

Can someone help me figure out how to delete an item by index in Angular? I have a parameter and a remove button, but when I tried putting my parameter inside the remove button it didn't work. How can I fix this? deleteRowFiles(rowIndex: number){ th ...

What is the best way to incorporate a 'category filter' in Angular2?

Unique Scenario In my Angular2 application, I have implemented code in a component's view parent.component.html that iterates through an array of items and generates a new component for each item: <div class="list-items"> <!-- The colored ...

When a URL is triggered via a browser notification in Angular 2, the target component ceases to function properly

Whenever I access a URL by clicking on a browser notification, the functionality of the page seems to stop working. To demonstrate this issue, I have a small project available here: https://github.com/bdwbdv/quickstart Expected behavior: after starting t ...

Caught off guard by this promise: TypeError - Attempting to access a property that does not exist in my Ionic 2 application

I'm encountering an issue with native Facebook login that displays the following error message: Uncaught (in promise): TypeError: Cannot read property 'apply' of undefined https://i.sstatic.net/PDWze.jpg I have shared my entire project ...