Reputation: 61
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
Reputation: 30
To get list of brands uniquely
const mapState = ({products}) => {
const brands = [...new Set( products
.map(product => product.brands))];
return { brands }
};
Upvotes: 1
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
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