我有一个JSON文件,如下所示:
{
"name1":
{
"fields":
{
"Name":
{
"type": "STRING"
},
"Email":
{
"type": "STRING"
},
"Password":
{
"type": "STRING"
},
"role":
{
"type": "STRING"
}
}
},
"name2":
{
"fields":
{
"url":
{
"type": "STRING"
}
}
},
"name1":
{
"fields":
{
"Address":
{
"type": "STRING"
}
}
}
}
我想迭代它,如果有一个已存在的名称,我想合并这些字段;这是我的代码:
var DBSchema = [];
async.each(Object.keys(config), function(key) {
var currentObject = config[key];
var DBSchemaTemp = [];
for (var field in currentObject.fields) {
if (currentObject.fields.hasOwnProperty(field)) {
DBSchemaTemp[field] = {AttributeName: field,
AttributeType: currentObject.fields[field].type
}
}
}
var arrayInSchema = DBSchema[key];
if (typeof arrayInSchema === 'undefined') {
DBSchema[key] = [];
DBSchema[key].push(DBSchemaTemp);
} else {
DBSchema[key].concat(DBSchemaTemp);
}
}, function(err) {
console.log(err);
});
for (variable in DBSchema) {
console.log(variable);
console.log(DBSchema[variable]);
}
我想要的输出是:
{
name1: [ Name: { AttributeName: 'Name', AttributeType: 'STRING' },
Email: { AttributeName: 'Email', AttributeType: 'STRING' },
Password: { AttributeName: 'Password', AttributeType: 'STRING' },
role: { AttributeName: 'role', AttributeType: 'STRING' } Address: { AttributeName: 'Address', AttributeType: 'STRING' } ]
name2: [ url: { AttributeName: 'url', AttributeType: 'STRING' } ]
}
但我的代码返回:
{ name1: [ [ Address: { AttributeName: 'Address', AttributeType: 'STRING' } ] ] name2: [ [ url: { AttributeName: 'url', AttributeType: 'STRING' } ] ] }
请注意;由于某种原因,它也增加了双[[]]!