Exploring the versatility of using multiple string arrays in TypeScript

I'm facing a simple problem that I just can't seem to solve. My goal is to extract data from a service and store it in an array, but no matter what I try, I can't get the desired outcome using properties or arrays.

For example:

abc~sdfgsdg|def~dgdfgdf|cvx~fgdfgfdh|

Sample Code:

let exampleText: string = 'abc~sdfgsdg|def~dgdfgdf|cvx~fgdfgfdh|'
let test: [string, string][];
let test2 = exampleTest.split('|');
test2.forEach(element => {
          let test3 = element.split('~'); 
          let t6 = test3[0]
          let t8 = test3[1]
          test.push(t6,t8)
        });

Error:

Argument of type 'string' is not assignable to parameter of type '[string, string]'.ts(2345)

An alternative approach:

let exampleText: string = 'abc~sdfgsdg|def~dgdfgdf|cvx~fgdfgfdh|'
let test: [Pro1:string,Pro2:string];
let test2 = exampleTest.split('|');
test2.forEach(element => {
          let test3 = element.split('~'); 
          let t6 = test3[0]
          let t8 = test3[1]
          test.push(t6,t8)
        });

Error:

TypeError: Cannot read properties of undefined (reading 'push')

The desired result:

console.log(test[0][0]) //print 'abc'
console.log(test[0][1]) //print 'sdfgsdg'
console.log(test[1][0]) //print 'def'
console.log(test[1][1]) //print 'dgdfgdf'

Or

console.log(test[0].Pro1) //print 'abc'
console.log(test[0].Pro2) //print 'sdfgsdg'
console.log(test[1].Pro1) //print 'def'
console.log(test[1].Pro2) //print 'dgdfgdf'

Answer №1

To start off, make sure you initialize the test array before attempting to push any values into it.

let test: [string, string][] = [];

The test array is designed to hold tuples of size 2 containing strings. Simply pushing a string directly won't work in this case. You'll need to create a tuple composed of t6 and t8, then push that instead.

test2.forEach((element) => {
  let test3 = element.split("~");
  let t6 = test3[0];
  let t8 = test3[1];
  test.push([t6, t8]);
});

Interactive Demo

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

Are JavaScript Object notation and proper JSON the same thing?

When I execute valid JSON in the Chrome console: {"aaa":"bbb"} I encounter this error: SyntaxError: Unexpected token : But if I try something like this instead: {aaa:"bbb"} No error is thrown. Additionally, when running the following code ...

Obtaining gender information by utilizing checkboxes in Angular 7

I have developed an Angular application that enables users to filter samples by gender using checkboxes. The options include male, female, or both genders selected. Currently, the filtering works for selecting either male or female individually, as well as ...

Develop a prototype function in ES6/ESNext with a distinct scope (avoid using an inline function)

Consider the following example: class Car { constructor(name) { this.kind = 'Car'; this.name = name; } printName() { console.log('this.name'); } } My goal is to define printName using a differe ...

Why does this switch case statement fail to effectively replace the elements of the text in order to unravel this JavaScript problem?

Question I need help converting special characters to HTML entities in a string: &, <, >, " (double quote), and ' (apostrophe). My Code function convertHTML(str) { let tempArr = ['a']; let newArr = []; let regex ...

Show SVG in its ViewBox dimensions

Currently, I am utilizing the img-Tag to showcase SVG images that have been uploaded by users onto my Amazon S3 storage. <img src="http://testbucket.s3.amazonaws.com/mysvg.svg" /> An issue arises once the image is displayed as it does not retain i ...

Error Alert: Accessing the 'email' property on the 'UserCredential' type in Angular and Firebase is not allowed

import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { User } from './../classes/user'; import { AlertService } from './alert.service'; import { Alert } from './../classes ...

recovering hidden components within an object

I've come across a data structure that contains embedded objects, presenting an interesting challenge: var object = { 'A' : {'cc' : { 'cc data 1' : 'data 1 cc for A', ...

How to remove elements from a JavaScript array: exploring the potential use of the delete function in JavaScript

I'm currently using Flot JS charts and I am attempting to completely remove a specific plot series from my data array either through jquery or plain javascript. Below is an example of what my data array consists of: [ { "label" : "Citrix PV Ether ...

The function startAfter() in Firebase Realtime Database (RTDB) does not seem

I'm currently implementing pagination for a list of items using Vuefire, and encountering an error with the following code snippet (the function works properly with startAt() but not with startAfter()) lastVisible is an object within my component&apo ...

The Precision of the IRR (Internal Rate of Return) Calculation in Javascript

I've been working on a custom IRR function in JavaScript to mimic the functionality of Excel's IRR function. Despite my best efforts, it seems that my results are slightly off. Below is the code snippet that I have been using: var IRRval = []; ...

Transform the appearance of buttons within AppBar using Material UI React

Embarking on a new project using React and Node JS has led me into the battle with Material UI. My current challenge is customizing the style of AppBar items, particularly the Buttons. Here's what I have in my "Menu" component: const Menu = () => ...

Enhance User Experience in IE11 by Providing Font Size Customization with Angular (Using CSS Variables)

I am in the process of developing an Angular application. One of the requirements is to allow the user to choose between small, medium, or large font sizes (with medium being the default) and adjust the font size across the entire webpage accordingly. Wh ...

The Vue.js page loads prior to the completion of the Axios request fetching data

Challenge I am facing an issue while trying to fetch data from my database using vuejs + axios within a Laravel project. Locally, the axios request works fine and the data is displayed on the DOM after assigning it to variables. However, when deploying th ...

The Backbone model destruction URL fails to include the model's ID when trying to delete

I'm facing an issue in my app where I need to delete a model from a collection using "this.model.destroy" in my view, but it triggers a 405 response and the response URL doesn't include the model's id. According to the Backbone documentation ...

JS/JQuery: Retrieve value from dropdown list or input field

I'm looking for a way for my user to choose a value from a drop-down menu, but if they can't find the right option there, I want them to be able to input a custom value. I've figured out a workaround by deactivating the drop-down and activa ...

How can I address the "z-index" issue with mesh materials?

Within my JSON model, I am aware of the two settings available for each material: depthTest and depthWrite. I have set these values to false because some materials contain RGBA textures, and setting them to true causes the alpha channel to match the backg ...

Determine the total number of matching values between two arrays across all distinct values within the arrays

I have two arrays A and B. A contains multiple values which can be of various types such as strings, integers, or floats, while B contains values of 0s and 1s. For every unique value in array A, I am aiming to determine the number of occurrences where the ...

Tips for extracting data from JSON values

My JSON Data Display let foodData = [{ meal_com_id: "1", name_company: "PeryCap", image: "https://shopgo.in/upload/1545849409-1518284057-Untitled-nn1.png", status: "1", description: "sdvaebfvhjaebfber itnwiuore tg5ykrgt wiretgi34 tgi3rgt ...

Angular 14 captures typed form data as `<any>` instead of the actual data types

On the latest version of Angular (version 14), I'm experiencing issues with strictly typed reactive forms that are not functioning as expected. The form initialization takes place within the ngOnInit using the injected FormBuilder. public form!: For ...

Superb Popup: hand-pick certain file formats

Is there a way to limit file selection to only jpg files when using magnific popup? $('.entry-content').each(function () { $(this).magnificPopup({ delegate: 'a', type: 'image' }); }); The issue I&apos ...