我希望根据嵌套JSON数据集中的级别重命名具有不同名称的变量。
示例JSON文件如下:
[
{
key: "John Doe School",
values: [
{
key: "Mr. Brown",
values: [
{
key: "Joe",
TestScore: 95
},
{
key: "Sarah",
TestScore: 99
}
]
}
]
}
]
在这个例子中,我想改变第一级"键"到"学校",第二级"键" to" Teacher",以及第三级" key"到#34;学生"。
JSON数据集在更改后将如下所示:
[
{
School: "John Doe School",
values: [
{
Teacher: "Mr. Brown",
values: [
{
Student: "Joe",
TestScore: 95
},
{
Student: "Sarah",
TestScore: 99
}
]
}
]
}
]
答案 0 :(得分:3)
嗯,举个例子,你可以这样做......
json[0]['School'] = json[0].key; // Add new key:value
delete json[0].key; // Delete previous one
json[0].values[0]['Teacher'] = json[0].values[0].key; // Add new key:value
delete json[0].values[0].key; // Delete previous one
json[0].values[0].values[0]['Student'] = json[0].values[0].values[0].key; // Add new key:value
delete json[0].values[0].values[0].key; // Delete previous one
json[0].values[0].values[1]['Student'] = json[0].values[0].values[1].key; // Add new key:value
delete json[0].values[0].values[1].key; // Delete previous one
更新以下评论
Template.Box.events({
'click .add button': function(e) {
e.preventDefault();
var target = {
...
};
Meteor.call('targetAdd', target, this._id, function(){});
}
});
Meteor.methods({
targetAdd: function(targetAttributes, boxId) {
check(this.userId, String);
check(boxId, String);
check(targetAttributes, {
...
});
var target = _.extend(targetAttributes, {
submitted: new Date(),
boxId: boxId
});
var targetId = Targets.insert(target);
return {
_id: targetId
};
}
});
Targets.after.insert(function () {
var targetId = this._id;
var boxId = this.boxId;
Boxes.update({_id:boxId}, {$addToSet: {targets: targetId}}, function () {
});
});
我假设你将循环遍历许多不同的JSON对象,所以你当然也需要实现它,但上面的结构应该指向正确的方向;)