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

时间:2018-12-11 08:02:33

标签: javascript html angular

我使用的是角形,我有一个对象数组,我们说Item(SmallItem, Bollean, Boolean),在我的代码中,我通过推动将元素添加到此数组中,例如:

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

但是,当且仅当Item中不存在具有相同smallItem的项目时,我才想推送Items。我该怎么办?

4 个答案:

答案 0 :(得分:1)

您可以简单地回到基础并按照这些原则做一些事情:

const itemToAdd = new Item(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););
}

答案 1 :(得分:0)

之后您可以删除其中带有smallItem的项目

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

答案 2 :(得分:0)

另一种方法可能是:

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

答案 3 :(得分:0)

尝试一下:

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