2016-03-13 95 views
1

我有一個這樣的對象:JSON數組動態柱填充AngularJs

var myObject= [ 
{"name":'Tom', "city":'Chicago',"GroupCode":'1'}, 
{"name":'Harry', "city":'Wisconsin',"GroupCode":'1'}, 
{"name":'Rob', "city":'Los Angeles',"GroupCode":'2'}, 
{"name":'Peter', "city":'Seattle',"GroupCode":'2'}, 
{"name":'Dave', "city":'New York',"GroupCode":'3'}, 
{"name":'Steve', "city":'Boston',"GroupCode":'3} 
]; 

變換爲

var myObject= [ 
    {"name":'Tom', "city":'Chicago',"GroupCode":'1'}, 
    {"name":'Harry', "city":'Wisconsin',"GroupCode":'1'}, 
    {"name":'--', "city":'--',"GroupCode":'--'}, 
    {"name":'Rob', "city":'Los Angeles',"GroupCode":'2'}, 
    {"name":'Peter', "city":'Seattle',"GroupCode":'2'}, 
    {"name":'--', "city":'--',"GroupCode":'--'}, 
    {"name":'Dave', "city":'New York',"GroupCode":'3'}, 
    {"name":'Steve', "city":'Boston',"GroupCode":'3} 
    ]; 

使用以下代碼來在當過GroupCode正在改變之間添加新的記錄:

var gc = myObject[0].GroupCode; 
myObject.forEach(function(ob, index) { 
    if (gc != ob.GroupCode) { 
    gc = ob.GroupCode; 
    //insert this object 
    myObject.splice(index, 0, { 
     "name": '--', 
     "city": '--', 
     "GroupCode": '--' 
    }); 
    } 
}) 

我如何使鑰匙/列在這裏動態?

myObject.splice(index, 0, { 
      "name": '--', 
      "city": '--', 
      "GroupCode": '--' 
     }); 

回答

1

你可以這樣說:

myObject.forEach(function(ob, index) { 
    if (gc != ob.GroupCode) { 
    gc = ob.GroupCode; 
    keys = Object.keys(ob); 
    var a = {}; 
    //dynamically creating keys in object 
    a[keys[0]] = '--' 
    a[keys[1]] = '--' 
    a[keys[2]] = '--' 
    //insert this object 
    myObject.splice(index, 0, a); 
    } 

}) 

工作代碼here

或者你也可以像這樣做太使它更有活力。

myObject.forEach(function(ob, index) { 
    if (gc != ob.GroupCode) { 
    gc = ob.GroupCode; 
    keys = Object.keys(ob); 
    var a = {}; 
    //iterate over keys and make object 
    keys.forEach(function(key){ 
     a[key] = '--' 
     a[key] = '--' 
     a[key] = '--' 
    }) 
    //insert this object 
    myObject.splice(index, 0, a); 
    } 

}) 

工作代碼here

+1

謝謝西里爾,這幫助了我。 – Srini