admin管理员组文章数量:1302417
I am using angular and I have an array of Objects let's say Item(SmallItem, Bollean, Boolean)
and in my code I add elements to this array by pushing, like for example:
this.Items.push(new Item(smallItem, false, true));
However, I would like to push an Item
if and only if item with the same smallItem
does not exist in Items
. How do I go about it?
I am using angular and I have an array of Objects let's say Item(SmallItem, Bollean, Boolean)
and in my code I add elements to this array by pushing, like for example:
this.Items.push(new Item(smallItem, false, true));
However, I would like to push an Item
if and only if item with the same smallItem
does not exist in Items
. How do I go about it?
- 1 You can use this.Items.find(x=>x.smallItems==whatever) (return undefined if not find it) – Eliseo Commented Dec 11, 2018 at 8:04
4 Answers
Reset to default 5You can simply go back to the basic and do something along thoses lines :
const itemToAdd = new Item(smallItem, false, true);
if(this.Items.findIndex((item) => item.smallItem === itemToAdd.smallItem) < 0) {
this.Items.push(itemToAdd);
}
or if you don't want to create the Item if it is not added :
if(this.Items.findIndex((item) => item.smallItem === smallItemToAdd) < 0) {
this.Items.push(new Item(smallItemToAdd, false, true););
}
You can remove the items afterward with smallItem in it like
Items.forEach((index,item)=>{
if(item.smallItem){
Items.splice(index,1)
)
an other approach could be:
var find = false;
for (let item of Items) {
// same smallItem value
if(item.smallItem) {
find = true;
}
}
if(!find) {
this.Items.push(new Item(smallItem, false, true));
}
Give this a try:
let items = [
{ name: 'Item 1', booleanA: true, booleanB: true },
{ name: 'Item 2', booleanA: true, booleanB: true },
{ name: 'Item 3', booleanA: true, booleanB: true },
{ name: 'Item 4', booleanA: true, booleanB: true },
{ name: 'Item 5', booleanA: true, booleanB: true }
];
function addItemIfNotAlreadyPresent(itemToAdd) {
let itemAlreadyExist = items.find(
item => item.name === itemToAdd.name && item.booleanA === itemToAdd.booleanA && item.booleanB === itemToAdd.booleanB
);
if(!itemAlreadyExist) {
items.push(itemToAdd);
}
}
let itemAlreadyPresent = { name: 'Item 1', booleanA: true, booleanB: true };
addItemIfNotAlreadyPresent(itemAlreadyPresent);
console.log('Items after trying to add itemAlreadyPresent: ', items);
let itemNotPresent = { name: 'Item 6', booleanA: true, booleanB: true };
addItemIfNotAlreadyPresent(itemNotPresent);
console.log('Items after trying to add itemNotPresent: ', items);
本文标签: javascriptAngular check if array contains object with specific variable valueStack Overflow
版权声明:本文标题:javascript - Angular check if array contains object with specific variable value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741681334a2392188.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论