简体   繁体   中英

How to map two arrays of objects, concatenate them, and add an index efficiently

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])
      }

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM