首页 > 解决方案 > 合并来自不同数据集的 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 
        });
    });
}

标签: javascriptarraysreactjsobject

解决方案


你可以做

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
       })
   })
}

让知道这是否有效。


推荐阅读