我有一个JSon对象数组,如下所示:
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}
];
我希望在GroupCode发生变化时添加一个包含一些示例值的新行。我的结果如下:
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}
];
我该怎么做?请帮忙!
答案 0 :(得分:2)
你可以这样做:
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'
}];
//store the first 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": '--'
});
}
})
console.log(myObject)
工作代码here