admin管理员组文章数量:1305712
I have an empty array and a selectable tree, and every time when the user is checking or un-checking a node I'm pushing the node's id and if the checkbox is true or false.
But right now if the user will check and then un-check a node there will be two objects in the array of the same node how can i make sure that doesn't happen?
//creating empty array
var checkedItems = [];
//(in kendo observable) on user selection I'm pushing the checked node to array
onItemChecked : function (e) {
var node = e.sender.dataItem(e.node);
checkedItems.push({Id: node.Id, IsChecked: node.checked});
},
I have an empty array and a selectable tree, and every time when the user is checking or un-checking a node I'm pushing the node's id and if the checkbox is true or false.
But right now if the user will check and then un-check a node there will be two objects in the array of the same node how can i make sure that doesn't happen?
//creating empty array
var checkedItems = [];
//(in kendo observable) on user selection I'm pushing the checked node to array
onItemChecked : function (e) {
var node = e.sender.dataItem(e.node);
checkedItems.push({Id: node.Id, IsChecked: node.checked});
},
Share
Improve this question
edited Jul 5, 2016 at 21:11
ManoDestra
6,5036 gold badges29 silver badges50 bronze badges
asked Jul 5, 2016 at 20:58
agDevagDev
8651 gold badge11 silver badges20 bronze badges
3 Answers
Reset to default 6You can, before pushing a new object, check the presence of an object that has that id.
var el = checkedItems.filter(function(el) {
return el.Id === node.Id;
});
if (el.length) {
el[0].IsChecked = node.checked;
} else {
// push a new object
}
You can just use an object, which is guaranteed to have unique keys:
var checkedItems = {};
onItemChecked : function (e) {
var node = e.sender.dataItem(e.node);
checkedItems[node.Id] = node.checked;
},
You have a Id which is grate, cuz that can be used for uniqueness. So maybe an array is not the best suited for what you want to acplish. There are better way to handle it with just plain object (see Mike McCaughan answer) and Map
var items = new Map
items.set(node.Id, node.checked)
// Removing items is as easy as
items.remove(node.Id)
// Getting
var checked = items.get(node.Id)
// Then if you want to iterate over them you would do something like:
for (var [key, value] of items.entries()) {
console.log(key + " = " + value)
}
var values = items.values()
var keys = items.keys()
Map's are like a key/value storage, much like object
本文标签: javascriptCheck if object exists in an array before pushingStack Overflow
版权声明:本文标题:javascript - Check if object exists in an array before pushing - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741809349a2398699.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论