在Typescript中过滤嵌套数组对象的数组

时间:2017-08-18 11:18:46

标签: javascript arrays angular filter

我在过滤嵌套数组数据时遇到了一些麻烦。例如,我有以下数据列表列表:

let list = [
{
  "percentage": 50.0,
  "budget": "online",
  "ruleName": "C1"
},
{
  "percentage": 50.0,
  "budget": "offline",
  "ruleName": "C1"
},
{
  "percentage": 50.0,
  "budget": "other",
  "ruleName": "C4"
}

现在我希望使用 .map .filter 来实现以下结果,并考虑父数组的预算属性和<的条件strong>子组数组匹配,那么它应该仅返回中匹配的对象而不是全部:

[
  {
    "budget": "online",
    "ruleName": "C1",
    "group": [
        {
            "budget": "onlne",
            "percentage": 50.0
        }
    ]
  },

  {
    "budget": "offline",
    "ruleName": "C1",
    "group": [
        {
            "budget": "offline",
            "percentage": 50.0
        }
    ]
  },

  {
    "budget": "other",
    "ruleName": "C4",
    "group": [
        {
            "budget": "other",
            "percentage": 0
        }
    ]
  }

所以我执行了以下操作,但我的结果与我上面的预期结果不符:

this.group = list.map((i)=>{
  return {
    budget: i.budget,
  }
})
this.payments = list.map((i)=>{
  return {
    budget: i.budget,
    amtPercentage: i.percentage ? i.percentage : 0,
    rulename: i.rulename,
    group: this.group
  }
})

以上是执行上述代码后的结果:

[
{
    "budget": "online",
    "ruleName": "C1",
    "group": [
        {
            "budget": "onlne",
            "percentage": 50.0
        },
        {
            "budget": "offline",
            "percentage": 50.0
        },
        {
            "budget": "other",
            "percentage": 0
        }
    ]
},

{
    "budget": "offline",
    "ruleName": "C1",
    "group": [
        {
            "budget": "onlne",
            "percentage": 50.0
        },
        {
            "budget": "offline",
            "percentage": 50.0
        },
        {
            "budget": "other",
            "percentage": 0
        }
    ]
},

{
    "budget": "other",
    "ruleName": "C4",
    "group": [
        {
            "budget": "onlne",
            "percentage": 50.0
        },
        {
            "budget": "offline",
            "percentage": 50.0
        },
        {
            "budget": "other",
            "percentage": 0
        }
    ]
}

]

我没有任何线索如何根据如果父数组预算属性等于group.budget属性的情况过滤嵌套组数组,那么它应该只返回该对象而不是全部。

我将非常感谢你的帮助。提前谢谢了。

注意:我使用的是带有angular-2的打字稿。

1 个答案:

答案 0 :(得分:4)

<html>
<head>
<style type="text/css">
@font-face {
    font-family: MyFont;
    src: url("file:///android_asset/fonts/bookerly.ttf")
}
body {
    font-family: MyFont;
    font-size: medium;
    text-align: justify;
}
</style>
</head>
<body>
Your text can go here
</body>
</html>