Javascript 角度检查数组是否包含具有特定变量值的对象

Javascript 角度检查数组是否包含具有特定变量值的对象,javascript,html,angular,Javascript,Html,Angular,我使用的是angular,我有一个对象数组,比如说Item(SmallItem,Bollean,Boolean),在我的代码中,我通过推动向这个数组添加元素,比如: this.Items.push(new Item(smallItem, false, true)); 但是,如果且仅当项目中不存在具有相同smallItem的项目时,我想推送项目。我该怎么做呢?您可以在之后删除包含smallItem的项目,如 Items.forEach((index,item)=>{ if(item.sma

我使用的是angular,我有一个对象数组,比如说
Item(SmallItem,Bollean,Boolean)
,在我的代码中,我通过推动向这个数组添加元素,比如:

this.Items.push(new Item(smallItem, false, true));

但是,如果且仅当
项目中不存在具有相同
smallItem
的项目时,我想推送
项目。我该怎么做呢?

您可以在之后删除包含smallItem的项目,如

Items.forEach((index,item)=>{
if(item.smallItem){
Items.splice(index,1)
)

另一种方法可以是:

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

你可以简单地回到基础,按照这些思路做一些事情:

const itemToAdd = new Item(smallItem, false, true);
if(this.Items.findIndex((item) => item.smallItem === itemToAdd.smallItem) < 0) {
    this.Items.push(itemToAdd);
}
const itemToAdd=新项(smallItem,false,true);
if(this.Items.findIndex((item)=>item.smallItem===itemToAdd.smallItem)<0){
this.Items.push(itemToAdd);
}
或者如果您不想创建未添加的项目:

if(this.Items.findIndex((item) => item.smallItem === smallItemToAdd) < 0) {
    this.Items.push(new Item(smallItemToAdd, false, true););
}
if(this.Items.findIndex((item)=>item.smallItem===smallItemToAdd)<0){
this.Items.push(新项(smallItemToAdd、false、true););
}
尝试一下:

let项目=[
{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}
];
函数addItemIfNotAlreadyPresent(itemToAdd){
让itemAlreadyExist=items.find(
item=>item.name===itemToAdd.name&&item.booleanA===itemToAdd.booleanA&&item.booleanB===itemToAdd.booleanB
);
如果(!itemAlreadyExist){
items.push(itemToAdd);
}
}
让itemAlreadyPresent={name:'Item 1',booleanA:true,booleanB:true};
addItemIfNotAlreadyPresent(itemAlreadyPresent);
log('尝试添加itemAlreadyPresent后的项:',项);
let itemNotPresent={name:'Item 6',booleanA:true,booleanB:true};
addItemIfNotAlreadyPresent(itemNotPresent);
log('尝试添加itemNotPresent后的项:',项)您可以使用这个.Items.find(x=>x.smallItems==which)(如果没有找到它,则返回undefined)