javascript - 从 React 的数组中排除已经存在的项目
问题描述
我正面临挑战。我在 firebase 中有 2 个表,需要合并到 1 个数组中。唯一的问题是项目是相同的,它们必须从数组中删除。因此,如果某个项目已经存在于数组中,则不应再将其添加到数组中。所以此刻我可以看到这些项目两次。有没有可能阻止这种情况?我的功能如下所示:
fetchItems(){
this.setState({
personalItems:[],
inactiveItems:[],
sprintItems:[],
})
let ref = Firebase.database().ref('/sprints/1/items/');
ref.on('value' , snapshot => {
snapshot.forEach((childSnap) => {
let state = childSnap.val();
console.log('firebase output:'+state)
var newelement = {title: state.title, author: state.author,user: state.user, public: state.public, x: state.x, y: state.y, key: state.key, match: state.match, notes: state.notes, status: state.status};
this.setState(prevState => ({
personalItems: [...prevState.personalItems, newelement],
}));
console.log('firebase'+state.name);
});
})
let refInactive = Firebase.database().ref('/users/'+this.state.user+'/items/');
refInactive.on('value' , snapshot => {
snapshot.forEach((childSnap) => {
let state = childSnap.val();
var newelement = {author: state.author, title: state.postit, status: state.status, key: state.key, user: state.user, match: state.match, x: state.x, y: state.y, public: state.public, notes:state.notes };
this.setState(prevState => ({
personalItems: [...prevState.personalItems, newelement],
}));
});
})
}
因此,您会看到这些项目具有相同的密钥。这些也彼此相同。但是,如果已经添加了 1,这就足够了,现在它们都被添加了。
解决方案
以下是如何将一个数组合并到另一个没有重复的数组。
for(arr1Element of array1){
if(!array2.some(arr2Element => arr2Element.id === arr1Element.id)){
array2.push(arr1Element)
}
}
推荐阅读
- sql - 如何将选择语句表述为某个属性是否达到某个域值;选择不存在的值
- apache-kafka - 如何从另一个流处理器访问 KStreams 物化状态存储
- linux - 来自emacs的Ubuntu Linux python绘图,无法从'PIL'导入名称'_imaging'
- java - 关于使用 CompletableFuture 的建议
- jquery - 对动态添加的项目进行排序
- android - 在android studio中以编程方式减少android设备的蓝牙范围
- node.js - 是否可以将 SSL 证书添加到现有部署?
- ruby-on-rails - 使用代理的请求被 Web 服务器阻止但浏览器没有
- mysql - 无法使用root登录phpMyAdmin,但可以从命令行访问MySQL
- recursion - Clojure - “get”和“nth”的混合?