Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How the proper way to transform object key array to normal object in TypeScript

I need to convert the posters object below to the normal array of objects but my code is not looking best any way to convert it proper in TypeScript.

and I don’t know what a poster’s object structure is called?

const posters = {
  facebook: ['aaa', 'bbb', 'ccc'],
  twitter: ['aaa', 'bbb', 'ccc'],
  instagram: ['aaa', 'bbb', 'ccc'],
  youtube: null,
  forum: null,
};

If some entity has null value will be not returned to the new object, an object will be like this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const posterTransformed = [
  { platform: 'facebook', name: ['aaa', 'bbb', 'ccc'] },
  { platform: 'twitter', name: ['aaa', 'bbb', 'ccc'] },
  { platform: 'instagram', name: ['aaa', 'bbb', 'ccc'] },
];

And this is my code

const transformPosters= (posters: any) => {
  const results = [];
  if (posters?.facebook)
    results.push({ platform: 'facebook', name: posters?.facebook || [] });
  if (posters?.twitter)
    results.push({ platform: 'twitter', name: posters?.twitter || [] });
  if (posters?.instagram)
    results.push({ platform: 'instagram', name: posters?.instagram || [] });
  if (posters?.youtube)
    results.push({ platform: 'youtube', name: posters?.youtube || [] });
  return results;
};

>Solution :

Here’s a functional approach for transforming the entries which have a non-null value:

TS Playground

type PostersObj = Record<string, string[] | null>;

type Poster = {
  platform: string;
  name: string[];
};

function transform <T extends PostersObj>(posters: T): Poster[] {
  const result: Poster[] = [];

  for (const [platform, name] of Object.entries(posters)) {
    if (!Array.isArray(name)) continue;
    result.push({platform, name});
  }

  return result;
}

const posters = {
  facebook: ['aaa', 'bbb', 'ccc'],
  twitter: ['aaa', 'bbb', 'ccc'],
  instagram: ['aaa', 'bbb', 'ccc'],
  youtube: null,
  forum: null,
};

const result = transform(posters);
console.log(result);
/*
[
  { "platform": "facebook", "name": ["aaa", "bbb", "ccc"] },
  { "platform": "twitter", "name": ["aaa", "bbb", "ccc"] },
  { "platform": "instagram", "name": ["aaa", "bbb", "ccc"] }
]
*/
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading