Home > OS >  Using multiple string arrays in Typescript
Using multiple string arrays in Typescript

Time:11-09

I have a very simple problem but I can't solve it. I want to shred the data from the service and throw it into the array, but I can't make it what I want, neither using property nor array.

Example Text: abc~sdfgsdg|def~dgdfgdf|cvx~fgdfgfdh|

Example 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)

Another way:

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 result I want:

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'

CodePudding user response:

First of all, you need to initialize the test array. Otherwise, you can't push into it.

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

test contains string tuples of size 2. Pushing a string into it won't work. You need to construct a tuple consisting of t6 and t8 and push it.

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

Playground

  • Related