M
M
Michael2015-10-11 11:07:24
JavaScript
Michael, 2015-10-11 11:07:24

How to check if an object is in an array?

Good afternoon!
How can you check if an object is in an array?
When I click, I add a product to the order array, the problem is that when I click on the same product again, it is added to the array again, how can I check whether it exists in the array or not?

addOrderList: function(index) {
            var product = this.products[index];
            this.order.orderList.push({product: product, count:1});
        }

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vitaly Inchin ☢, 2015-10-11
@xmentor

You can check by matching property values:

var productBox = [{product: "Рыба", count: 10}];

function addTo(product, count){
   var cond = productBox.some(function(e){ 
        return e.product == product;
   });

   if(cond){
      alert("Такой продукт уже есть");
      //Но лучше просто увеличивать count у продукта
   }else{
      productBox.push({product:product, count:count});
   }
}

addTo("Водка", 5);
addTo("Мясо", 3);
addTo("Шампур", 10);
addTo("Водка", 22);

A
amatory10, 2015-10-11
@amatory10

objects can be compared for example using: JSON.stringify(object)

V
Vladimir Io, 2015-10-11
@vawsan

There are no special functions for comparing objects in JS.
You can use something like:
https://github.com/rikkimongoose/JSonCmp/
If you know exactly the position of the object in the array, you only compare it, if not, then you pick up objects throughout the array and compare them with the incoming one.

E
Evgeny Petrov, 2015-10-11
@EvgenZZ

underscore. js

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question