问题描述
我使用cursor.observechange,这样,无论何时添加记录,它都会在UI上通知.记录类型: {"ref":"100","status":进行中"}
我有一个空数组
Iam using cursor.observechange such that when ever a record is added,it notifies on UI.recordtype: {"ref":"100","status":"inprogress"}
I have an empty array
var arr=[];
每当我需要检查状态是否正在进行中并且ref在arr []中的任何对象中都不存在时.如果是这样,则需要将其推入arr
When ever I need to check if status is inprogress and that ref doesnt exist in any object in arr[]..If so then I need to push that to arr
arr.push(obj);
如果状态已完成,并且ref已经存在于arr []中,那么我需要从arr []中删除它下面是我尝试过的
If that status is complete and if ref already exists in arr[],then I need to delete that from arr[]Below is that i tried
var arr = [];
function addObject(obj){
if(!arr.some(function(el){return (el.ref === obj.ref)}))
{
arr.push(obj);
}
else if{
arr.slice(el);
}
}
var cursor = TransactionDetails.find({ });
cursor.observeChanges({
added: function(id, object) {
if (object.status == "incomplete") {
addObject(object);
Notification.error("added");
}
else if(object.status == "complete" {
addObject(object);
Notification.error("modified");
}
}
});
但是这不起作用.我们如何根据这种情况添加和删除.有任何帮助.谢谢!
But this is not working.How can we add and delete based on that conditions.Any help.Thanks!
推荐答案
您可以使用函数从数组 arr
中删除对象.
You could use a function for removing an object from the array arr
.
它使用 Array#findIndex
function removeObject(obj) {
var index = arr.findIndex(o => o.ref === obj.ref);
if (index !== -1) {
arr.splice(index, 1);
}
}
或带有 Array#some
function removeObject(obj) {
function getIndex(el, i) {
if (el.ref === obj.ref) {
index = i;
return true;
}
}
var index;
if (arr.some(getIndex)) {
arr.splice(index, 1);
}
}
这篇关于如何基于事件在json数组中添加和删除对象(cursor.observeChanges)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!