Search code examples
javascriptarrayswordpress-rest-api

How to fetch items in a map function for each ID


I am trying to fetch some data with the Wordpress API and i need to do this based on the restbase and ID.

I have an array that looks like this:

const array = [
    {
        taxonomy: 'category',
        rest_base: 'categories',
        id: [ 1, 2 ]
    },
    {
        taxonomy: 'post_tag',
        rest_base: 'tags',
        id: [ 4, 5, 6, 7 ]
    }
];

This is the map function:

array.map( ({ rest_base, id }) => {
    console.log( rest_base ); // categories or tags
    console.log( id ); // array of id's

    // Do a call here for each id
});

I need to somehow get all the individual ID's so i can make calls like:

example.com/wp-json/wp/v2/<rest_base>/<id>

Can anybody help me with that?


Solution

  • Iterate the outer array with Array.flatMap() and the id array with Array.map() make the calls with fetch or similar APIs, and you'll get an array of promises:

    const array = [{"taxonomy":"category","rest_base":"categories","id":[1,2]},{"taxonomy":"post_tag","rest_base":"tags","id":[4,5,6,7]}];
    
    const result = array.flatMap( ({ rest_base, id }) => 
      id.map(v => `example.com/wp-json/wp/v2/${rest_base}/${v}`) // wrap the string with a fetch or similar function
    );
    
    console.log(result);

    If you can't use Array.flatMap() use nested Array.map() call, and flatten by spreading into Array.concat():

    const array = [{"taxonomy":"category","rest_base":"categories","id":[1,2]},{"taxonomy":"post_tag","rest_base":"tags","id":[4,5,6,7]}];
    
    const result = [].concat(...array.map( ({ rest_base, id }) => 
      id.map(v => `example.com/wp-json/wp/v2/${rest_base}/${v}`) // wrap the string with a fetch or similar function
    ));
    
    console.log(result);