我知道有幾十個類似的問題標題,但我找不到解決我問題的問題。
關鍵是我避免對資料庫進行不必要的查詢。因此,當進行查詢時,只消耗需要的內容。我獲取資料并將其與 LocalStorage 合并以節省使用量。
我創建了這個示例以使其更易于閱讀并幫助未來的用戶:
let usersDB = [
{ id: 1, name: 'John', age: 34 },
{ id: 2, name: 'Rose', age: 27 },
{ id: 3, name: 'Daniel', age: 40 },
]
const usersLS = [
{ id: 1, name: 'John', cars: ['BMW', 'Ferrari'] },
{ id: 2, name: 'Rose', cars: ['Tesla', 'Camaro'] },
{ id: 4, name: 'Ambrose', cars: ['Fiat'] },
]
/** Expected Result:
* [
* {id: 1, name: 'John', cars: ['BMW', 'Ferrari']},
* {id: 2, name: 'Rose', cars: ['Tesla', 'Camaro']},
* {id: 3, name: 'Daniel'},
* ]
*/
在上面的例子,userDB并userLS表示所述資料庫和用戶的localStorage分別。
自然,userDB是最“更新”的,但userLS有一個屬性“汽車”,它與資料庫中的用戶不在同一個表中。所以我需要更新userLS使用userDB作為基礎,但不會丟失“汽車”屬性。
我知道我可以做一個 for...loop 來迭代用戶,并在其中,另一個 for...loop 檢查 id 是否相同,然后生成一個包含物件的新陣列。但是,我相信必須有更好的方法來解決這個問題。
編輯:我嘗試過的
let newArr = [];
for (let userDB of usersDB) {
for (let userLS of usersLS) {
if (userDB.id === userLS.id) {
userDB.cars = userLS.cars
newArr.push(userDB);
}
}
}
usersDB = Object.assign([...usersDB], ...newArr)
上面的代碼是我用來解決這個問題的方法。你能想出更直接的解決方案嗎?
uj5u.com熱心網友回復:
您可以Array.map()在 usersDB 陣列上使用,然后將屬性與為任何給定用戶找到的任何 userLS 合并。
我們將使用擴展語法來合并陣列中的每個專案:
const usersDB = [
{ id: 1, name: 'John', age: 34 },
{ id: 2, name: 'Rose', age: 27 },
{ id: 3, name: 'Daniel', age: 40 },
]
const usersLS = [
{ id: 1, name: 'John', cars: ['BMW', 'Ferrari'] },
{ id: 2, name: 'Rose', cars: ['Tesla', 'Camaro'] },
{ id: 4, name: 'Ambrose', cars: ['Fiat'] },
]
const result = usersDB.map(( { age, ...userDB}, idx) => {
let userLS = usersLS.find(u => u.id === userDB.id);
return { ...userLS, ...userDB};
}, {})
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
Array.map 會有所幫助
let usersDB = [
{ id: 1, name: 'John', age: 34 },
{ id: 2, name: 'Rose', age: 27 },
{ id: 3, name: 'Daniel', age: 40 },
]
const usersLS = [
{ id: 1, name: 'John', cars: ['BMW', 'Ferrari'] },
{ id: 2, name: 'Rose', cars: ['Tesla', 'Camaro'] },
{ id: 4, name: 'Ambrose', cars: ['Fiat'] },
];
const userConsolidated = usersDB.map((user) => {
const cars = usersLS.find((item) => item.id === user.id);
const { id, name } = user;
const returnNode = { id, name };
if (cars) returnNode.cars = cars;
return returnNode
});
console.log(userConsolidated);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/409196.html
標籤:
下一篇:從生成器中獲取生成器函式的名稱
