Reputation: 100
I have two different arrays of objects that need to be mapped individually to key:value pairs defined by me. When mapping, each of the objects should be assigned a sequential index. Then, I need to take each of the mapped arrays and concatenate them.
This is what I've tried so far. It works, but I think there might be a more efficient or clean way to do it:
const mapPosts = () => {
let index = 0
const mappedPostsA = postsA.map(post => {
index++
return {
id: index,
provider: 'Wordpress',
post_id: postA.id,
title: postA.title,
body: postA.body_html
}
})
const mappedPostsB = postsB.map(post => {
index++
return {
id: index,
provider: 'Blogspot',
post_id: postB.id,
title: postB.title,
body: postB.description
}
})
const mappedPosts = [...mappedPostsA, ...mappedPostsB])
}
Upvotes: 1
Views: 238
Reputation: 664307
To remove code duplication, I'd probably do
const mappedPostsA = postsA.map(post => ({post, provider: 'Wordpress', body: post.body_html}));
const mappedPostsB = postsB.map(post => ({post, provider: 'Blogspot', body: post.description}));
const mappedPosts = [].concat(mappedPostsA, mappedPostsB).map(({post, provider, body}, index) => ({
id: index,
provider,
post_id: post.id,
title: post.title,
body,
}));
Upvotes: 0
Reputation: 3408
You could just offset the index by the length of postsA
, as you know postsB
will always be right after it.
const mapPosts = (postsA, postsB) => {
return [
...postsA.map((post, index) => ({
id: index,
provider: 'Wordpress',
post_id: post.id,
title: post.title,
body: post.body_html
}))
...postsB.map((product, index) => ({
id: index + postsA.length,
provider: 'Blogspot',
post_id: product.id,
title: product.title,
body: product.description
}))
];
};
I used the spread syntax since you used it in your original question, you could use something like mappedA.concat(mappedB)
instead, but this is mostly a matter of preference.
Upvotes: 4
Reputation: 99
If you're concerned about efficiency, and if you have a lot of objects, you might want to consider using a Map instead of a plain object. Maps are specifically tailored to efficiently handle key-value pairs. You might get a slight performance boost, or at least slightly more readable code.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
Upvotes: 0