3 回答

TA貢獻1829條經驗 獲得超13個贊
這可能更適合代碼審查,但如果問題只是“如何使其更簡潔”,我會建議如下所示:
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",
? }]
}]
const findItem = function(shelves, id) {
? return shelves.flatMap((shelf) => shelf.articleList).find((article) => article.id == id) || null;
}
console.log(findItem(shelf, 1));
console.log(findItem(shelf, 3));
上面的示例連接所有文章列表,然后在該數組中搜索具有提供的 ID 的文章。
性能方面?不是最好的,但您要求一些簡潔的東西,這大約是給定數據結構所希望的盡可能簡潔。

TA貢獻1856條經驗 獲得超5個贊
這段代碼的復雜度是 O(1),這意味著查找 perarticle.id是常數。但是它會使用更多內存。為了節省內存,我使用了WeakMap,只要你使用同一個shelf變量,它就不會重新計算它。但一旦替換它,它也會從緩存中消失。
const shelf = [{
"categoryPrice": "2",
"categoryTitle": "Flyer",
"articleList": [{
"id": "1",
"articleTitle": "Green",
}, {
"id": "2",
"articleTitle": "Blue",
}, {
"id": "3", // Added
"articleTitle": "Violet",
}],
}, {
"categoryPrice": "3",
"categoryTitle": "Post card",
"articleList": [{
"id": "3",
"articleTitle": "Purple"
}, {
"id": "4",
"articleTitle": "Yellow",
}],
}];
const findItems = function(shelves, id) {
if (!findItems._map) {
// Create computation cache holder
// Weak map will make sure, that if the object is disposed, it can be garbage collected, with it will be gone its cache too! (That is awsome!)
findItems._map = new WeakMap();
}
if (!findItems._map.has(shelves)) {
// For every shelves object, we will create a new Map containing all mapped values.
const map = new Map();
findItems._map.set(shelves, map);
shelves.forEach(shelf => {
shelf.articleList.forEach(article => {
if (!map.has(article.id)) {
// If list is not yet created create it with the article
return map.set(article.id, [ article ]);
}
// If it exists, add to it
map.get(article.id).push(article);
});
});
}
return findItems._map.get(shelves).get(id);
}
console.log(findItems(shelf, "1"));
console.log(findItems(shelf, "3"));

TA貢獻1811條經驗 獲得超4個贊
你可以通過循環兩次來逃脫。一次用于外部數組,一次用于articleList數組
const findItem = (id) =>
shelf.reduce((acc, current) => {
const found = current.articleList.find((x) => x.id === id);
if (found) return [...acc, found];
return acc;
}, []);
添加回答
舉報