2014-09-29 55 views
0

我在这里绞尽脑汁,需要一些快速帮助。如何返回对象,如果它包含JavaScript中的一个字母

我有以下的JSON对象:

"product": { 
    "diagnostics": null, 
     "skus": [{ 
      "itemCode": "Q28988", 
      "salesCode": "Q2898800", 
      "listPrice": 22, 
      "salePrice": 22, 
      "numberOfBottles": 1, 
      "salePricePerBottle": 22, 
      "id": "esku580806", 
      "vppApplier": false, 
      "vppPrice": null, 
      "vppDiscountPct": null 
     }, { 
      "itemCode": "C28988", 
      "salesCode": "C2898800", 
      "listPrice": 264, 
      "salePrice": 264, 
      "numberOfBottles": 12, 
      "salePricePerBottle": 22, 
      "id": "esku580811", 
      "vppApplier": false, 
      "vppPrice": null, 
      "vppDiscountPct": null 
     }], 
      "id": "eprod440905", 
} 

,我需要过滤的SKU阵列,只返回以字母“Q”开头itemCodes。我使用下划线和JavaScript,这是我能得到的最接近的,但它似乎没有返回任何东西。

var codes = _.filter($scope.cb.recommendations, function(obj){ 
      var startLetter = obj.product.skus.slice(); 
      return startLetter[0] === 'Q'; 
     }); 

$ scope.cb.recommendations是JSON对象 - 片段在上面。十分感谢!

+0

难道你不想看看“itemCode”字段,而不仅仅是SKU对象的数组吗? – Pointy 2014-09-29 22:30:15

+0

是的,我确实 - 但不知道该怎么做?是吗? obj.product.skus []。itemCode - 但似乎失败 – jrutter 2014-09-29 22:32:13

+0

什么是'$ scope.cb.recommendations'?似乎你想过滤'obj.product.skus'。你希望结果是那些具有以'Q'开头的'itemCode'的sku元素,还是你想要一个项目代码数组? – 2014-09-29 22:32:38

回答

1

你不解释什么$scope.cb.recommendations是,所以我会展示如何过滤一个产品的skus阵列。诀窍是第三个参数传递给_.filter它获取结合至this谓词函数内部:

var codes = []; 
_.filter(
    obj.product.skus, 
    function(sku) { 
     if (sku.itemCode[0] === 'Q') { 
      this.push(sku.itemCode); 
     } 
    }, 
    codes 
); 
0

没有下划线并且如果仅1“Q-项”可能存在:

function findQ(skus) { 
    var len = skus.length; 
    while(len--) { 
    if(skus[len].itemCode.indexOf('Q') === 0) 
     return skus[len]; 
    } 
} 

var item = findQ(json.product.skus); 

http://jsfiddle.net/8pb13cdj/

相关问题