Search code examples
angulartypescriptangular-reactive-formsangular-forms

How to restructure the Object to specific format in Angular


I need to restructure the current object what i'm getting from API response to desired object.

Current Output


let temp = [
    {
      "imagePath": "",
      "imageDescription": [
        {
          "language": "en",
          "text": "Today's News Updated"
        }
      ]
    },
    {
      "imagePath": "",
      "imageDescription": [
        {
          "language": "en",
          "text": "test"
        }
      ]
    },
    {
      "imagePath": "",
      "imageDescription": [
        {
          "language": "de",
          "text": "test"
        }
      ]
    },
   
  
 
  ]

Desired output

let temp = {
"imagesList": {
    "en": [{
       "imagePath": "",
       "text": "Today's News Updated"
     },
     {
       "imagePath": "",
       "text": "test"
     }],
     "de": [{
       "imagePath": "",
       "text": "test"
     }]
   }
}

How to achieve this in angular by typescript so that i can render in the view

Please find the below Sandbox Link Sandbox Link


Solution

  • Typescript Playground Link

    interface InputImage {
        imagePath: string;
        imageDescription: InputDescription[];
    }
    
    type Language = "en" | "de";
    
    interface InputDescription {
        language: Language;
        text: string;
    }
    
    let temp: InputImage[] = [
        {
            "imagePath": "",
            "imageDescription": [
                {
                    "language": "en",
                    "text": "Today's News Updated"
                }
            ]
        },
        {
            "imagePath": "",
            "imageDescription": [
                {
                    "language": "en",
                    "text": "test"
                }
            ]
        },
        {
            "imagePath": "",
            "imageDescription": [
                {
                    "language": "de",
                    "text": "test"
                }
            ]
        },
    ]
    
    interface ImageWithDescription {
        imagePath: string,
        text: string,
    }
    
    interface Result {
        imagesList: {
            [key in Language]?: ImageWithDescription[];
        }
    }
    
    const result = temp.reduce<Result>((acc, val) => {
        const { imagesList } = acc;
        const { imagePath, imageDescription } = val;
        for (const { language, text } of imageDescription) {
            if (!(language in imagesList)) {
                imagesList[language] = [{ imagePath, text }];
                continue;
            }
            
            (imagesList[language] as ImageWithDescription[]).push({
                imagePath,
                text
            })
        }
    
        return acc;
    }, { imagesList: {} });
    
    console.log(result);