Search code examples
reactjstypescriptdictionaryobject

Map an Object to an array using react typescript


this object is taken from a form that has input, output and outputType which can change from number String and Boolean

I have created the mapped obj so that i can show it in a table without outputype but i also want to take it to an edit page where i need as an array listed at the bottom with its type

      const mapped = form.values.formValue.reduce((obj: ValueMaped, { input, outputType, output }) => {
    let parsedOutput: ValMap['output']

    switch (outputType) {
      case 'String':
        parsedOutput = output.toString()
        break

      case 'Number':
        parsedOutput = parseFloat(output.toString())
        break

      case 'Boolean':
        parsedOutput = Boolean(output)
        break
    }

    obj[input] = parsedOutput

    return obj
  }, {})
  onSave(mapped)

I have an obj = mapped im am getting the result as below

{
  valueA: 'sample value as string',
  valueB: 123,
  valueC: true
}

how can i map and convert it to an array as below

[
  { input: 'valueA', outputType: 'String', output: 'sample value as string' },
]

Solution

  • With Object.entries, we can map over the keys and values simultaneously:

    const result = Object.entries(obj).map(([input, output]) => ({ input, output, outputType: capitalize(typeof output) }));
    

    I've also chosen to use a utility to capitalize the result from typeof:

    function capitalize(s: string) { return s[0].toUpperCase() + s.slice(1); }
    

    The output generated for your example object looks like

    [{
      "input": "valueA",
      "output": "sample value as string",
      "outputType": "String"
    }, {
      "input": "valueB",
      "output": 123,
      "outputType": "Number"
    }, {
      "input": "valueC",
      "output": true,
      "outputType": "Boolean"
    }] 
    

    const obj = {
        valueA: "sample value as string",
        valueB: 123,
        valueC: true,
    };
    
    function capitalize(s) { return s[0].toUpperCase() + s.slice(1); }
    
    const result = Object.entries(obj).map(([input, output]) => ({ input, output, outputType: capitalize(typeof output) }));
    
    console.log(result);

    Playground


    P.S. Consider using all-lowercase for the outputType:

    const result = Object.entries(obj).map(([input, output]) => ({ input, output, outputType: typeof output }));
    

    It'll remove the need for extra code to capitalize it. You would then also need to update your switch statement to reflect this:

    switch (outputType) {
        case 'string':
            parsedOutput = output.toString()
            break
    
        // ...
    }