Michal Kurowski
Michal Kurowski

Reputation: 61

How can I map specific props to state?

I'm trying to map specific props to the brands state. Also, don't add values that already exist in the brands state.

Goal output:

brands: [
  "IKEA",
  "Tesla"
]

My attempt

const mapState = (state) => ({
  brands: state.products.forEach(product => {
    if (product.brands) {
      return product.brands;
    }
  })
});

export default connect(mapState)(Brands);

State:

products: [
  {
    "id": 1,
    "title": "Pen",
    "brands": "IKEA"
  },
  {
    "id": 2,
    "title": "Flamethrower",
    "brands": "Tesla"
  },
  {
    "id": 3,
    "title": "T-shirt",
    "brands": "Tesla"
  }
]

Upvotes: 1

Views: 134

Answers (3)

Umer Bhat
Umer Bhat

Reputation: 30

To get list of brands uniquely

const mapState = ({products}) => {
  const brands = [...new Set( products
     .map(product => product.brands))];
  return { brands }
};

Upvotes: 1

ljbc1994
ljbc1994

Reputation: 2254

You can do the following by using .reduce[1] to build up an array of distinct products.

const mapState = (state) => ({
  brands: state
     .products
     .reduce((brands, product) => {
        if (!brands.includes(product.brands)) {
           return brands.concat([product.brands]);
        }
        return brands;
     }, [])
  })
});

export default connect(mapState)(Brands);

You can extract retrieving distinct brands into a function if you need to reuse this in your application:

function getProductBrands(products) {
   return products
     .reduce((brands, product) => {
        if (!brands.includes(product.brands)) {
           return brands.concat([product.brands]);
        }
        return brands;
     }, []);
}

References: [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Upvotes: 3

Bob van 't Padje
Bob van 't Padje

Reputation: 734

forEach does not return anything. What you could do is create a function getAllProductBrands and call this function. This function should then return a list of all brands.

const getAllProductBrands = (products) => {
  const brands = [];
  products.forEach(product => {
    if(!brands.some(brand => brand === product.brand) {
      brands = [...brands, product.brand];    
    };
  });
};

You can then call this function in your mapState.

const mapState = (state) => ({
  brands: getAllProductBrands(state.products)
});

Upvotes: 2

Related Questions