我有一个像这样的对象:
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": '--'
});
答案 0 :(得分: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