javascript - 合并来自不同数据集的 js 对象值
问题描述
我有 2 个数据点 Firebase 和一个包含图像和键的本地对象数组。
我想做的是检查来自后端的 id 是否与本地图像键匹配,如果为 true,则将图像与 id 一起添加到用户状态。
const userAvatars = [
{ image: require('../images/user1.png'), key: 'user1' },
{ image: require('../images/user2.png'), key: 'user2' },
{ image: require('../images/user3.png'), key: 'user3' },
{ image: require('../images/user4.png'), key: 'user4' },
]
这是我为用户设置状态的地方,我想拥有
{id: userID, image: userAvatars.image}
_createUsersList = () => {
this.data = firebase.database().ref('filters/users');
this.data.once('value').then(snapshot => {
const items = [];
snapshot.forEach((snapshot) => {
items.push({
id: snapshot.val(),
image: snapshot.val() == userAvatars.key ? userAvatars.image : null
});
});
this.setState({
users: items
});
});
}
解决方案
你可以做
const matchedAvatars = userAvatars.filter((avatar) => {
return avatar.key == snapshot.val();
});
if(matchedAvatars && matchedAvatars.length > 0){
matchedAvatars.forEach((avtr) => {
items.push({
id: snapshot.val(),
image: avtr.image
})
})
}
让知道这是否有效。
推荐阅读
- pyspark - 从 databricks notebook pyspark 连接 Synapse/Azure sql db
- javascript - 运行“react-native run-android”时出错
- keycloak - keycloak javascript适配器中的回调事件顺序
- python - 使用列表更新 2D numpy 数组中的特定位置
- mysql - 错误:通信链接失败 java.lang.NullPointerException
- c# - 从代码运行 NUnit 测试(以编程方式)
- python - MQTT 客户端变量证书字符串
- bash - 重击;文件内容不超过
- vuejs2 - Vue 2 和 Vuetify 不能改变排水沟
- r - 如何修复错误“匹配错误(x,表,nomatch = 0L):'匹配'需要向量参数”?