0

I am building an ionic 4 app which has to save multiple labels and arrays to an associative array but having trouble with initializing and pushing new items to the array and editing/updating existing array items in the associative array.

  array1 = {
           'Question1'=>['True','True'],
           'Question2'=>['False, False'] 
           }

How can I do this in typescript?

2
  • You might be comming from PHP where this is possible, but JS (and TS) does not support string keys for arrays. You can use objects or a maps (where strings can be keys). obj: { [key: string]: string[] } = { key1: ["1a", "1b"] } or see stackoverflow.com/questions/30019542/es6-map-in-typescript Commented Oct 9, 2020 at 6:49
  • Thanks @Klímačka. Yeah i came from a PHP background I thought it would be possible since I am new to typescript. Let me look into mapping in typescript Commented Oct 9, 2020 at 8:47

1 Answer 1

1

JavaScript/TypeScript does not support arrays with named indexes, arrays always use numbered indexes. You can, however, use a simple object to do this, e.g.:

    const questions = {
        "question1": [true, true],
        "question2": [false, false]
    }
    
    console.log(questions);
    console.log(questions["question1"]) // prints [true, true]

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

2 Comments

Thanks @eol, I will look into numbered indexes. I was also advised to look into mapping in typescript
@appdevnoobie: Happy to help, don't forget to accept this answer (by clicking the checkmark to the left) if this solved your problem.

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.