Helmi
Helmi

Reputation: 539

merge data between objects, match key values

Here's a sample of the data

featuredPosts = [
  { 'order': 1, 'id': 23 },
  { 'order': 2, 'id': 12 }, 
]

and here's the more complex data

allPosts = [
  { 'id': 12, 'title': '...', 'content': '...' },
  { 'id': 13, 'title': '...', 'content': '...' },
  ...
  { 'id': 23, 'title': '...', 'content': '...' },
  ...
]

Is there a way to merge data from allPosts into featuredPosts only for the id's existing in featured Posts already without looping through featured posts and through the keys of allPosts? I mean is there a smarter way to do so?

Upvotes: 0

Views: 39

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138247

Just build up a hashtable (id -> featuredPost):

 const hash = {};
 for(const featuredPost of featuredPosts)
   hash[featuredPost.id] = featuredPost;

Then go over allPosts and look them up in the hashtable:

 for(const post of allPosts)
   if(hash[post.id]) Object.assign(hash[post.id], post);

Now featuredPosts contains the merged data.

Upvotes: 1

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48337

You can use reduce method by passing a callback function as argument in combination with Object.assign method.

featuredPosts = [
  { 'order': 1, 'id': 23 },
  { 'order': 2, 'id': 12 },
]
allPosts = [
  { 'id': 12, 'title': '...', 'content': '...' },
  { 'id': 13, 'title': '...', 'content': '...' },
  { 'id': 23, 'title': '...', 'content': '...' }
]

var merged = featuredPosts.concat(allPosts).reduce((acc, x) => {
    acc[x.id] = Object.assign(acc[x.id] || {}, x);
    return acc;
}, {});
console.log(Object.keys(merged).map(key => merged[key]));

Upvotes: 0

Related Questions