I've been trying to wrap my head around filtering arrays of objects for a while now, but I can't seem to really get a hang on it. Although I usually have working code in the end, it just doesn't look like elegant code to me. So, I'd appreciate a code review and some hints very much!
Example: I'm currently working on this example for an online shop where I need to retrieve product details out of an array of objects based on an id.
This is my helper function:
function getItemDetails(id) {
var getCategory = shelf.filter(obj => obj.articleList.some(cat => cat.id === id));
var getArticleList = getCategory[0].articleList;
var getItem = getArticleList.filter(item => item.id == id);
return getItem
}
Steps: In a first step, I tried to filter the shelf array, but it would return the entire array articleList of the corresponding item.
So, I filtered the result again with the same criteria and it works, but it just looks awfully redundant to me.
This is an example of the data:
const shelf = [{
"categoryPrice": "2",
"categoryTitle": "Flyer",
"articleList": [{
"id": "1",
"articleTitle": "Green",
}, {
"id": "2",
"articleTitle": "Blue",
}],
}, {
"categoryPrice": "3",
"categoryTitle": "Post card",
"articleList": [{
"id": "3",
"articleTitle": "Purple"
}, {
"id": "4",
"articleTitle": "Yellow",
}]
}]
I checked various questions here, including:
But none of them provide an easier, more concise solution, in my opinion. What am I missing?
Thanks for your help!