I have a foreach loop and I'm adding key value pairs to my DBSchema, but when I use "DBSchema.push({key: DBSchemaTemp})", it does not put the real value of "key" and instead is pushing the word "key"; how can I solve the problem?
var DBSchema = [];
async.each(Object.keys(config.models), function(key) {
var DBSchemaTemp = [];
.
.
Working on DBSchemaTemp
.
.
DBSchema.push({key: DBSchemaTemp});
});
The result is like the following:
[ { key: [ [Object], [Object], [Object], [Object] ] },
{ key: [ [Object] ] },
{ key: [ [Object] ] },
{ key: [ [Object], [Object], [Object], [Object] ] } ]
EDITED: Desired output:
{ name1: [ [Object], [Object], [Object], [Object] ] ,
name2: [ [Object] ] ,
name3: [ [Object] ] ,
name4: [ [Object], [Object], [Object], [Object] ] }
or:
{ name1: { [Object], [Object], [Object], [Object] } ,
name2: { [Object] } ,
name3: { [Object] } ,
name4: { [Object], [Object], [Object], [Object] } }
After using the solution by Hamilton:
var arrayInSchema = DBSchema[key];
if(typeof arrayInSchema === 'undefined') DBSchema[key] = [];
DBSchema[key].push(DBSchemaTemp);
{ user:
[ [ Name: { AttributeName: 'Name', AttributeType: 'STRING' },
Email: { AttributeName: 'Email', AttributeType: 'STRING' },
Password: { AttributeName: 'Password', AttributeType: 'STRING' },
role: { AttributeName: 'role', AttributeType: 'STRING' } ] ]
name2:
[ [ url: { AttributeName: 'url', AttributeType: 'STRING' } ] ]
name3:
[ [ Name: { AttributeName: 'Name', AttributeType: 'STRING' },
Caption: { AttributeName: 'Caption', AttributeType: 'STRING' },
url: { AttributeName: 'url', AttributeType: 'collection' } ] ]
name4:
[ [ media: { AttributeName: 'media', AttributeType: 'collection' } ] }
But there is a duplicate parenthesis! Also by "Is it also possible to merge with the previous result if already that key exist?" I mean if in another itteration again if we push the following, it should merge it with the previous result which already exist:
user: [ Address: { AttributeName: 'Name', AttributeType: 'STRING' }]
I guess the problem is duplicate paranthesis; I dont know how they are coming; If I did not have them, the following should work:
var arrayInSchema = DBSchema[key];
if (typeof arrayInSchema === 'undefined') {
DBSchema[key] = [];
DBSchema[key].push(DBSchemaTemp);
} else {
DBSchema[key].concat(DBSchemaTemp);
}
Thanks