简体   繁体   中英

How to store all including repeating(non-unique) object in javascript array?

I want to store and display all(including repeated) objects but it only stores distinct(unique) values.

The good thing is total is adding all the values including reoccurring The Bad thing is indistinctresult cannot store reoccurring object
for loop also does not work

if (req.isAuthenticated()) {
    User.find({ _id: req.user._id }, function (err, cartitem) {
      var noofcartitem = cartitem[0].cart_array.length;

      product.find({ _id: cartitem[0].cart_array }, function (err, result) {
        var total = 0;
        var x;
        var indistinctresult = [];  ***//stores only distinct(Unique) values*** 
        for (x in result) {
          total += result[x].price;
          indistinctresult.push(result[x]);
        }
        console.log(indistinctresult); **//expected to log all(including non unique) values**
        res.render("cart", {
          cart_array: noofcartitem,
          total: total,
          cartproduct: indistinctresult,
        });
      });
    });
  } else {
    res.redirect("/login");
  }

I see you are using for..in loop for iterating through array. It's not a good idea.

The following link might be helpful to you.

Why is using "for...in" for array iteration a bad idea?

const x = [1, 2, 3, 1]
const y = []
for (let i=0; i<x.length; i++) {
    y.push(x[i]);  
}
console.log(y);

OUTPUT: [1, 2, 3, 1]
Replace you for..in loop with for loop with index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM