2016-11-27 60 views
0

我有一個問題在Ionic/AngularJs:如何使用Ionic/AngularJs在對象數組上搜索特定字段?

我有兩個搜索對象,無法正常工作。 第一個if (cartObj.cart.find (id)! = - 1) {--->這沒關係。

第二個是if(cartObj.cart.findvovo(supply_id)!= - 1)如果第一個if的值等於我要獲取的字段接受的值。

我想僅從「cart_item_supply」提取數據:supply_id。我怎樣才能做到這一點?

enter image description here

在屏幕連接我告訴我的控制檯與數組對象爲你更好地理解。

這是我的代碼:

var cartObj = {}; 
cartObj.cart=[]; 
cartObj.total_amount=0; 
cartObj.total_qty=0; 


// VERIFICA DE JÁ EXISTE ITENS NO CARRINHO 
cartObj.cart.add=function(id,image,name,price,qty,supply_id,deliver){ 
    if(cartObj.cart.find(id)!=-1 ){ 
     var alertPopup = $ionicPopup.alert({ 
      title: 'This product has already been added', 
      template: 'Add more quantity to cart' 

     }); 

    }if(cartObj.cart.findvovo(supply_id) !=-1){ 
     var alertPopup = $ionicPopup.alert({ 
      title: 'This offer is from Another Grandmother', 
      template: 'You can only buy offers from a single Grandma. Choose other offers from this same Grandma.' 
     }); 
    } 

    // IF DON´T EXIST, ADD 
    else{ 
     cartObj.cart.push({ "cart_item_id": id , "cart_item_image": image , "cart_item_name": name , "cart_item_price": price , "cart_item_qty": qty, "cart_item_supply": supply_id, "cart_item_deliver": deliver }); 
     cartObj.total_qty+=1; 
     cartObj.total_amount+=parseInt(price); 
     console.log(cartObj); 
    } 
}; 

// SEACH PRODUCTS BY ID 
cartObj.cart.find=function(id){ 
    console.log("chamou find"); 
    var result=-1; 
    for(var i = 0, len = cartObj.cart.length; i < len; i++) { 
     if(cartObj.cart[i].cart_item_id === id) { 
      result = i; 
      console.log(result); 
      break; 
     } 
    } 
    return result;   
}; 

// SEARCH CART_ITEM_SUPPLY === SUPPLY_ID --- HERE DONT FOUND 
cartObj.cart.findvovo=function(supply_id){   
    var result=-1; 
    for(var i = 0, len = cartObj.cart.length; i < len; i++) {    
     if(cartObj.cart[i].cart_item_supply === supply_id) {    
      result = i; 
      console.log(result); 
      break; 
     } 
    }; 
    return result; 
}; 

能做些什麼解決這個問題?

的especific代碼是在這裏:

// SEARCH CART_ITEM_SUPPLY === SUPPLY_ID --- HERE DONT FOUND 
cartObj.cart.findvovo=function(supply_id){   
    var result=-1; 
    for(var i = 0, len = cartObj.cart.length; i < len; i++) {    
     if(cartObj.cart[i].cart_item_supply === supply_id) {    
      result = i; 
      console.log(result); 
      break; 
     } 
    }; 
    return result; 
}; 

回答

1

使用功能_.every從lodash

https://lodash.com/docs/4.17.2#every


@Edit(基於評論) _.some(yourArray,{cart_item_supply: yourValue})

這個Wi會回報你TRUE如果陣列將這個你會發現有更多的yourValuehttps://lodash.com/docs/4.17.4#some

+0

嗨@DiPix我現在使用lodash。是工作。但是我不能得到第一個id,只能從其他寄存器獲得這個第一個id。 – Ramos

+0

你能舉個例子嗎?集合,你的lodash查詢和預期結果? – DiPix

+0

創建對象的開始沒有任何內容。用戶選擇一個產品並創建第一個對象數組。所以,他選擇了另一種產品。如果這個新產品具有與數組「cart_item_supply」字段相同的值,那麼可以創建一個新對象,否則顯示一條消息並且不會創建一個新對象。 – Ramos

相關問題