将项目推送到对象数组 - javascript

时间:2016-02-17 20:11:37

标签: javascript angularjs

更新:我尝试从我的数据结构(即section1)构建一个表,然后允许用户向表中添加行以插入更多行并将其保存到我的数据结构中。

我以键值对的形式有一个数组 newArr 。当有人点击按钮时,我希望能够将newArray推入Groups.I似乎无法进入Groups数组。 Chrome开发工具将群组显示为对象,并且我不确定如何循环并附加到群组对象的每个项目。您可以随意将$ scope.section1修改为不同的数据结构,以便更轻松地将新项目推送到该数据结构。

$scope.section1 = [{
                "id":1, "Name": "Section 1: Inventory",
                 "Groups":[
                     {"cell" : "Number", "cellValue" : "value1"}, 
                     {"cell" : "Location", "cellValue" : "value2"}, 
                     {"cell" : "Severity", "cellValue" : "value3"}
                 ],
                 "FootNotes":[
                    {"templateurl" : "components/section/templates/notes/section1.notes.html"}
                 ]  
            }]

        var newArr = {"cellValue" : "value4","cellValue" : "value5","cellValue" : "value6"}

所以输出应该看起来像

 $scope.section1 = [{
                    "id":1, "Name": "Section 1: Inventory",
                     "Groups":[
                         {"cell" : "Number", "cellValue" : "value1", "cellValue" : "value4"}, 
                         {"cell" : "Location", "cellValue" : "value2", "cellValue" : "value5"}, 
                         {"cell" : "Severity", "cellValue" : "value3", "cellValue" : "value6"}
                     ],
                     "FootNotes":[
                        {"templateurl" : "components/section/templates/notes/section1.notes.html"}
                     ]  
                }]

2 个答案:

答案 0 :(得分:1)

您不能拥有两个同名的媒体资源。对象组有两次cellValue。你想做什么?

您最好更改结构本身:

...
"Groups": [
    { 
        name: "group1",
        values: ['value 1', 'value 2', 'value 3']
    }
]

然后,再向group1添加一个值:

$scope.section1[0].Groups.values.push('value 4')

请注意,我试图尊重您已有的整个结构,但我并不认为这是解决问题的最佳方式

答案 1 :(得分:0)

$scope.section1[0].Groups.push({
  "cell" : "Number", 
  "cellValue" : "value1", 
  "anotherCellValue" : "value4"
});