嵌套数组没有返回最深的obj

时间:2015-07-23 17:20:29

标签: javascript lodash

我正在使用lodash,我正在尝试获取嵌套在数组中的对象。我需要的是betTypes,因此我使用var needDeepestObj

betTypes放到_.filter
var deepestObj = function(betSlipData) {

  var needDeepestObj = 

    _.filter(betSlipData.customerBetTypes, function(betIndex) {
      return _.filter(betIndex.betTypes, function(betTypes) {
         console.log('1', betTypes); //returns what I need
         return betTypes;
      });
    });

    console.log('2', needDeepestObj);
   //returns only the first _.filter with param *betIndex*
};

那么,我如何才能达到包含betTypes的范围?

这是betIndex param在我的浏览器控制台中返回的内容。

{
  "header": {
    "name": "Straights",
    "priority": "1"
  },
  "betTypes": [
    {
      "id": "1",
      "name": "Straight",
      "buyPoints": "Y",
      "maxPoints": "3",
      "minPoints": "0",
      "isAvailable": "1",
      "placeBetIsAvailable": "1",
      "reasonPlaceBetNotAvailable": "",
      "isSelected": "0",
      "priority": 1
    }
  ],
  "header": {
    "name": "Straights",
    "priority": "1"
  },
  "betTypes": [
    {
      "id": "1",
      "name": "Straight",
      "buyPoints": "Y",
      "maxPoints": "3",
      "minPoints": "0",
      "isAvailable": "1",
      "placeBetIsAvailable": "1",
      "reasonPlaceBetNotAvailable": "",
      "isSelected": "0",
      "priority": 1
    }
  ],
  "header": {
    "name": "Straights",
    "priority": "1"
  },
  "betTypes": [
    {
      "id": "1",
      "name": "Straight",
      "buyPoints": "Y",
      "maxPoints": "3",
      "minPoints": "0",
      "isAvailable": "1",
      "placeBetIsAvailable": "1",
      "reasonPlaceBetNotAvailable": "",
      "isSelected": "0",
      "priority": 1
    }
  ],
  "header": {
    "name": "Straights",
    "priority": "1"
  },
  "betTypes": [
    {
      "id": "1",
      "name": "Straight",
      "buyPoints": "Y",
      "maxPoints": "3",
      "minPoints": "0",
      "isAvailable": "1",
      "placeBetIsAvailable": "1",
      "reasonPlaceBetNotAvailable": "",
      "isSelected": "0",
      "priority": 1
    }
  ]
}

所以,我需要的是betTypes,而betIndex会返回我上面粘贴的JSON。

更新

显然,它是一个非常大的JSON,其中包含类似的千个“标题”和“betTypes”属性。但我需要迭代该JSON才能只处理一次该属性。

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全按照您的提问。 我的回答是假设L:

betSlipData.customerBetTypes = [{ header: {}, betTypes: [{}] }, ...]

然后它非常简单:

var needDeepestObj = _(betSlipData.customerBetTypes).map(function (bet) {
    return bet.betTypes;
}).flatten().value();

这将在每次下注中产生每个betTypes数组中的所有对象的数组。

如果您可以显示betSlipData.customerBetTypes是什么以及您要查找的确切结果的示例,无论是数组还是对象,特定键等,都会有很大帮助。

您在寻找特定的betType吗?