Map wordpress post from array

So I have the following function:

/**
 * Get array of post objects
 *
 * @param slug
 */
function get_array_of_post_objects(slug)
{
    let items = [];
    wp.api.loadPromise.done(function () {
        const Posts = wp.api.models.Post.extend({
            url: wpApiSettings.root + 'menus/v1/locations/' + slug,
        });
        const all_posts = new Posts();
        all_posts.fetch().then((posts) => {
            items.push(...posts.items);
        });
    });
    return items;
}

When invoked like this:

const test = get_array_of_post_objects('application_launcher');
console.log(test);

Gives me an array of objects as shown below:
enter image description here


Question:

What would be a good way to map my objects? Let’s say that I want to map just the ID and db_id.. what’s a good approach? I haven’t messed with mapping too much, so have some learning to do.

Here is what I was messing with:

const test2 = test.map((ID, db_id) => {
    return {
        ID,
        DBID: db_id,
    }
});

1 thought on “Map wordpress post from array”

  1. In javascript you would do it like so:

    const test2 = test.map((obj) => {
      return {ID: obj.ID, DBID: obj.db_id};
    });
    

    A callback for the map function takes each element of the array as the first param.

    Reply

Leave a Comment