skip to Main Content

I have a string array & need to create key & value like below….

const output = { string1: true, string2: true,  string3: true };

Example

const strarray  = ["string1","string2","string3"];

I need output like

const output = { string1: true, string2: true,  string3: true };

How to achieve in React-Typescript?

2

Answers


  1. You can use reduce method to generate object from array of string

    const strarray  = ["string1","string2","string3"];
    
    const output = strarray.reduce((c,data)=>{
     c[data] = true;
     return c; 
    },{})
    
    console.log(output)
    .as-console-wrapper { max-height: 100% !important; }
    Login or Signup to reply.
  2. I understand the question is how can I achieve in react-ts. so I think it is easy. the above answer was correct but there are some linting errors. I want to suggest like:

      type objType = Record<string, boolean>;
      const strarray: string[] = ["string1", "string2", "string3"];
      const output: objType = strarray.reduce((c: objType, data: string) => {
        c[data] = true;
        return c;
      }, {});
    
      console.log(typeof output);
      console.log(output)
    

    hope that can help your listing error. *** cause there are too many edits. I write it as a answer. #credit above answer

    example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search