我知道有很多类似这个题目的题目,但我找不到解决我问题的题目。
关键是我避免了对数据库的不必要查询。因此,当查询完成时,只消耗所需的内容。我获取数据并将其与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
有一个属性"cars“,它与数据库中的用户不在同一表中。因此,我需要使用userLS
作为基础更新userDB
,但不会丢失"cars“属性。
我知道我可以做一个for...loop来迭代用户,在这个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)
上面的代码就是我用来解决这个问题的方法。你能想出更直接的解决办法吗?
发布于 2022-01-12 04:54:04
您可以在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; }
发布于 2022-01-12 04:55:52
Array.map
会帮上忙
逻辑
usersDB
数组用Array.map
循环usersLS
数组中查找比较id的匹配节点cars
属性从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 usersLSnode = usersLS.find((item) => item.id === user.id);
const { id, name } = user;
const returnNode = { id, name };
if (usersLSnode) returnNode.cars = usersLSnode.cars;
return returnNode
});
console.log(userConsolidated);
https://stackoverflow.com/questions/70681441
复制