将值从JSON对象推送到数组

时间:2015-02-26 09:48:56

标签: arrays json angularjs object

我的AngularJS控制器中有以下对象:

  {"team":"1","name":"abc","age":"20"},
  {"team":"1","name2":"def","age2":"21"},
  {"team":"2","name":"ghi","age":"22"},
  {"team":"2","name2":"jkl","age2":"23"},

我需要通过团队密钥将项目分组到一个数组对象中。

  {
   "team": [
     {"name1":"abc","age1":"20", "name2":"def", "age2":"21"},
     {"name1":"ghi","age1":"22", "name2":"jkl", "age2":"23"}
   ]
  }

所以我以后可以使用$ scope.data.team [1] .name2

等信息 编辑:顺便说一句,一支队伍总是由4名队员组成。 我该怎么做?

1 个答案:

答案 0 :(得分:1)

编辑:根据您的需求工作plunkr:http://plnkr.co/edit/zxoOYV?p=preview

你应该重新安排你的结构。即你可以选择这样的东西:

{"team": [
    {"players": [
        {"name" : "abc", "age": 20},
        {"name" : "def", "age": 34},
    ]},
    {"players": [
        {"name" : "abc", "age": 20},
        {"name" : "def", "age": 34},
    ]}
]}

如果您在控制器中使用此结构:

$scope.team = {...}

并在你的html中使用它:

<div ng-controller="TeamController">
    <div ng-repeat="players in team">
       <div ng-repeat="player in players">
          <div>Name: {{player.name}}</div>
          <div>Name: {{player.age}}</div>
       </div>
    </div>
</div>

所以,对于你的例子,我得到了angular-schema-form。

使用上述结构,架构如下所示:

[
  {
    "type": "help",
    "helpvalue": "<h4>Tabbed Array Example</h4><p>Tab arrays can have tabs to the left, top or right.</p>"
  },
  {
    "key": "team",
    "type": "tabarray",
    "add": "New",
    "remove": "Delete",
    "style": {
      "remove": "btn-danger"
    },
    "title": "value.name || 'Team '+$index",
    "items": [
        {
        "key": "team[].players",
        "title": "Players",
        "items": [
          {
            "key": "team[].players[].name",
            "title": "Name"
          },
          {
            "key": "team[].players[].age",
            "title": "Age"
          }
    ]
  }
    ]
  },
  {
    "type": "submit",
    "style": "btn-default",
    "title": "OK"
  }
]

和相应的架构:

{
  "type": "object",
  "title": "Team",
  "properties": {
    "team": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
            "players": {
              "type": "array",
              "maxItems": 4,
              "items": {
                "type": "object",
                "properties": {
                  "name": {
                    "type": "string"
                  },
                  "age": {
                    "type": "integer"
                  }
                },
                "required": [
                  "name",
                  "age"
                ]
              }
            }
        },
        "required": [
          "players"
        ]
      }
    }
  }
}