typescriptdictionarycollectionsmerge

How to merge Dictionarys from typescript-collection?


I have installed the typescript-collection package to my Angular project to use the Dictionary type. I want to save all latest posts from Socialmedia in a Dictionary with the Date the image was posted. After this I want to merge alle the Dictionarys into one Dictionary.

let TwitterPosts = this.getLatestTwitterPosts();
let InstagramPosts = this.getLatestInstagramPosts();
let FacebookPosts = this.getLatestsFacebookPosts();

The getLatests[type]Posts-Methods are like this:

const type = 'twitter';
let TwitterPosts = new Collections.Dictionary<number, PostSocialmediaFeedComponent>();
for (let count = 0; count < 10; count++) {
  let PostedDate: Date;
  let url: string;
  // USING THE API TO GET THE VALUES
  TwitterPosts.setValue(count, new PostSocialmediaFeedComponent(url, PostedDate, type));
}
return TwitterPosts;

Solution

  • Just use a simple object and merging becomes trivial and syntactically supported at that. Don't waste your time with complex libraries you don't need.

    const type = 'twitter';
    const twitterPosts: {[key: number]: PostSocialmediaFeedComponent} = {};
    for (let count = 0; count < 10; count++) {
      // USING THE API TO GET THE VALUES
      twitterPosts[count] = new PostSocialmediaFeedComponent(url, PostedDate, type);
    }
    return TwitterPosts;
    

    In addition to simplifying dependencies and making your code more straightforward, using simple objects gives you syntactic support for trivial merging via object spread ....

    const twitterPosts = this.getLatestTwitterPosts();
    const instagramPosts = this.getLatestInstagramPosts();
    const facebookPosts = this.getLatestsFacebookPosts();
    
    const merged = {
      ...twitterPosts,
      ...instagramPosts,
      ...facebookPosts
    };
    

    This is effectively syntactic sugar for the built in ECMAScript standard library functionality of Object.assign (details on MDN)

    const merged = Object.assign({}, twitterPosts, instagramPosts, facebookPosts);