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?

Share edited Dec 11, 2018 at 8:32 Nikolai Kiefer 6136 silver badges21 bronze badges asked Dec 11, 2018 at 8:02 Maciej MiśkiewiczMaciej Miśkiewicz 4122 gold badges9 silver badges22 bronze badges 1
  • 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
Add a ment  | 

4 Answers 4

Reset to default 5

You 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