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

Time:10-11

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.

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;
};

CodePudding user response:

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"] }
]
*/

CodePudding user response:

I like to use reduce when I need to loop over something and omit some values in the result. I might try something like this:

const transformedPosters = Object.keys(posters).reduce((acc, currentKey) => {
  const value = posters[currentKey];
  if (value && value.length) {
    acc.push(
      {
        platform: currentKey,
        name: value
      }
    )
  }

  return acc
}, [])

console.log(transformedPosters)

// output 
[
  { platform: 'facebook', name: [ 'aaa', 'bbb', 'ccc' ] },
  { platform: 'twitter', name: [ 'aaa', 'bbb', 'ccc' ] },
  { platform: 'instagram', name: [ 'aaa', 'bbb', 'ccc' ] }
]

  • Related