Search code examples
javascriptarraysreactjsmappingjavascript-objects

How to dynamically render content based on object property and path in url


I have an object array like this:

const products = [
{
name: 'prod1',
category: 'cat1',
pageID: 'product-001',
},{
name: 'prod1',
category: 'cat1',
pageID: 'product-001',
},{
name: 'prod1',
category: 'cat1',
pageID: 'product-001',
}];

And I'm rendering those as a product list on in my app. Every position on the rendered product list should link to specific product view. So far I came up with the pageID property, that is passed to link as props. Works fine - paths are correct.

Problem I have: When trying to render a specific product view, I'm mapping my object array. How do I check if my window.location.pathname is the same as one of the object's pageID, and then get the name and category of only this object?


Solution

  • Just reduce that array into an object with the keys being the pageID and the values being an object of name, category:

    const products = [{
      name: 'prod1',
      category: 'cat1',
      pageID: 'product-001'
    }, {
      name: 'prod2',
      category: 'cat2',
      pageID: 'product-002'
    }, {
      name: 'prod2',
      category: 'cat2',
      pageID: 'product-002'
    }];
    
    const pageIDs = products.reduce((a, { name, category, pageID }) => ({ ...a, [pageID]: { name, category }}), {});
    
    let windowPathname = "product-002";
    
    console.log(pageIDs[windowPathname]);

    (I edited your sample data to show that it works)