2

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'

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Oh finally. I've been trying for 2 hours on this little thing. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.