define an object in javascript - javascript

I am new to javascript.
I want to have an object with this structure.
Users = {
User1 : {
"name" : "name",
"id" : "123"
}
User2 : {
"name" : "name",
"id" : "123"
}
}
so I should define Users like this:
var Users = {};
How can I add new User to Users? and How can I read and write from users inside Users object like this:
// reading
User1_name = Users.User1.name;
// writing
Users.User1.name = "new name";

Your code is fine (except the missing comma #Philipp pointed), but you can use an array too:
var users = [
{
"name" : "name",
"id" : "123"
},
{
"name" : "name",
"id" : "123"
}
];
var userName = users[0].name;
users[0].name = "new name";

You can define users like this, you are just missing a comma
Users = {
User1 : {
"name" : "name",
"id" : "123"
} <--
User2 : {
"name" : "name",
"id" : "123"
}
}
Should be ( with var added for clarity )
var Users = {
User1 : {
"name" : "name",
"id" : "123"
},
User2 : {
"name" : "name",
"id" : "123"
}
}
Reading and writing can be done the way you described.
To add a new user, you could do something like this
Users["User3"] = {
"name" : "name3",
"id" : "1234"
}

Related

How can I access(and convert) 'date' to Javascript?

Here is MongoDB scheme.
{
"_id" : ObjectId("222222"),
"active" : false,
"amount" : "15%",
"description" : "15% discount",
"name" : "20200628-test",
"policies" : {
"apply" : [
{
"name" : "expiryDate",
"params" : {
"date" : ISODate("2020-07-06T14:59:59.999Z")
}
},
{
"name" : "isApplyCategoryExist"
}
],
"discount" : [],
"conflict" : [
{
"name" : "exclusive"
}
],
"grant" : []
},
"target" : {
"sku" : "",
"products_ids" : [],
"category_ids" : [
ObjectId("11111111")
]
},
"title" : "15% coupon"
}
I want to access date.
For example, "policies.apply.params.date"...
I don't know how to access 'date' to Javascript.
Please let me know...
apply is an array, so you have to give it index which you want to get.
var num = 0; // pick up an array number you want
var date = policies.apply[num].params.date;
Your policies.apply is an array so if you want to access "2020-07-06T14:59:59.999Z", you should do this:
policies.apply[0].params.date
But the "policies.apply[1]" doesn't have params (params.date also) so you can write a function to get date like this:
function get_apply_date(index) {
if(policies.apply[index].params && policies.apply[index].params.date)
return policies.apply[index].params.date;
return undefined; // or null
}

$ref in Json Schema with specified values

I'm trying to build a schema that references another schema. However in my schema I would like to specify that certain properties specified by the referenced schema have particular values without modifying that referenced schema.
For example with a schema like this:
{
"definitions" : {
"name" : {
"properties" : {
"firstName" : { "type" : "string" },
"lastName" : { "type" : "string" }
},
"required" : ["firstName", "lastName"]
}
},
"properties" : {
"clientName" : { "$ref" : "#/definitions/name" }
},
"required" : [ "clientName" ]
}
I would somehow like to validate objects that have firstName equal to "Bob".
So this should validate:
{
"clientName" : {
"firstName" : "Bob",
"lastName" : "Doe"
}
}
But this should not:
{
"clientName" : {
"firstName" : "Fred",
"lastName" : "Doe"
}
}
Without modifying the "definitions" block in my schema, how can I express this restriction?

Is there any javascript library to represent json-result of #JsonIdentityInfo?

I have 2 bi-directional models and I use JsonIdentityInfo to prevention from infinite Recursion in json result. Here is my viewmodels:
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class GroupsViewModel extends BaseEntityViewModel<Long> {
private String title;
private Set<UserViewModel> users;
}
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class UserViewModel extends BaseEntityViewModel<Long> {
private String username;
private String password;
private Set<GroupsViewModel> groups;
}
and a part of my json result is like below:
[{
"id" : 1,
"title" : "adminGroup",
"users" : [{
"id" : 1,
"username" : "admin",
"password" : "...",
"groups" : [1]
}, {
"id" : 31,
"username" : "user78",
"password" : "...",
"groups" : [1]
}, {
"id" : 3,
"username" : "ali",
"password" : "...",
"groups" : [{
"id" : 2,
"title" : "newsWriterGroup",
"users" : [{
"id" : 14,
"username" : "staff1",
"password" : "...",
"groups" : [{
"id" : 1005,
"title" : "FileManagerAccessGroup",
"users" : [{
"id" : 25,
"username" : "test1",
"password" : "...",
"groups" : [1005, {
"id" : 1006,
"title" : "noAccessGroup",
"users" : [25, {
"id" : 26,
"username" : "test5",
"password" : "...",
"groups" : [1006]
}
]
}
]
}, 14]
}, 2]
}, ...
As shown in above, if object is repetitive in json result, Jackson put only it's identifier of it. Now I want to know Is there any javascript/jquery library to represent json-result of #JsonIdentityInfo? for example, when javascript/jquery library arrive at 1005 identifier , it automaticaly load group object with id = 1005.
It's very unlikely that such a targeted library exists. You could easily write a function though that deconstructs the data back into an array of users and groups by using typeof checking, and then using recursion when a new object is encountered in the groups or users attributes.
Just be careful when printing out the results that you don't create a circular reference. See this question for help on that.
function Group(group) {
this.id = group.id;
this.title = group.title;
this.users = [];
Group.cache[this.id] = this;
group.users.forEach(this.addUser, this);
}
Group.cache = {};
Group.prototype.addUser = function(user) {
this.users.push(
typeof user === 'number'
? User.cache[user]
: new User(user)
);
};
function User(user) {
this.id = user.id;
this.username = user.username;
this.password = user.password;
this.groups = [];
User.cache[this.id] = this;
user.groups.forEach(this.addGroup, this);
}
User.cache = {};
User.prototype.addGroup = function(group) {
this.groups.push(
typeof group === 'number'
? Group.cache[group]
: new Group(group)
);
};
// begins the recursion
JSON.parse(
'[{"id":1,"title":"adminGroup","users":[{"id":1,"username":"admin","password":"...","groups":[1]},{"id":31,"username":"user78","password":"...","groups":[1]},{"id":3,"username":"ali","password":"...","groups":[{"id":2,"title":"newsWriterGroup","users":[{"id":14,"username":"staff1","password":"...","groups":[{"id":1005,"title":"FileManagerAccessGroup","users":[{"id":25,"username":"test1","password":"...","groups":[1005]},14]},2]},3]},1]}]}]'
).forEach(function(group) { new Group(group) });
function stopCircularWithId(key, value) {
return key === 'users' || key === 'groups'
? value.map(function(u) { return u.id })
: value;
}
console.log('groups:', JSON.stringify(Group.cache, stopCircularWithId, 4));
console.log('users:', JSON.stringify(User.cache, stopCircularWithId, 4));
JSFiddle

Updating array inside two object in mongod

I have a collection of the structure as follows:
collection name : "positions"
Structure
{
"_id" : "vtQ3tFXg8THF3TNBc",
"candidatesActions" : {
"sourced" : [ ],
},
"appFormObject" : {
"name" : "✶ mandatory",
"questions" : [
{
"qusId" : "qs-585494",
"type" : "simple",
"qus" : "Which was your previous company"
},
{
"qusId" : "qs-867766",
"type" : "yesNo",
"qus" : "Are you willing to relocate?",
"disqualify" : "true"
}
]
}
}
I want to update "qus" field of the above collection whose _id is "vtQ3tFXg8THF3TNBc" and "qusId" is "qs-585494".
Try following....
db.positions.update(
{_id: "vtQ3tFXg8THF3TNBc", "appFormObject.questions.qusId":"qs-585494"},
{$set:{"appFormObject.questions.$.qus": "this is updated value"}}
)
Use following query
db.positions.findAndModify({
query: { _id: "vtQ3tFXg8THF3TNBc", "appFormObject.questions.qusId":"qs-585494"} ,
update: { $set: { 'appFormObject.questions.$.qus': 'Brilliant Green' } },
});
Thanks

Mongodb structure operation

Another day. Another Mongodb query.
I wish to create the following structure in once of my collections:
amitverma is the user and the nested object is message's UTC timestamp. I want to push messages in the following structure.
{
"username" : "macbook",
"messages" : {
"amitverma" : {
"1383321755" : {
"to" : "macbook",
"message" : "hi.",
"sender" : "amitverma",
},
"1383321712" : {
"to" : "macbook",
"message" : "hi.",
"sender" : "amitverma",
}
}
},
"_id" : ObjectId("5273d09ab743db7a5f000001")
}
I cant use $push or $addToSet as it isnt an array. Or can I?
Also, I have the following code right now:
var pushNotification = {};
var addon = {};
var anotheraddon = {};
var utcTime = arrayOps.encodeTime();
addon[data.sender] = [];
anotheraddon[utcTime] = data;
addon[data.sender].push(anotheraddon);
// var a = pushNotification;
// a.push(anotheraddon);
// console.log(pushNotification);
pushNotification['messages'] = {}
pushNotification['messages'][data.sender] = [];
pushNotification['messages'][data.sender] = data;
var a = 'messages.' + data.sender + '.$';
console.log('push object');
console.log(pushNotification);
co_notifications.update(
{'username': data.to},
{ $addToSet: pushNotification}, function(err, docs){
console.log(err);
console.log(docs);
if (docs == 0){
co_notifications.insert(
{'username': data.to, 'messages': addon}, function(er, doc){
});
}
},
{upsert: true}
);
Excuse the garbage code. The above code results in this structure:
{
"username" : "macbook",
"messages" : {
"amitverma" : [
{
"1383321755" : {
"to" : "macbook",
"message" : "hi.",
"sender" : "amitverma",
}
}
]
},
"_id" : ObjectId("5273d09ab743db7a5f000001")
}
which isn't exactly what I desire.
Is there a way I can create the structure I want and also read and update from the same easily? Thanks.
You can insert additional elements of the form you outlined above to
an existing document by using the following update:
info = {"to": "...", "message": "...", "sender": "..."}
c.update({}, {$set: {'messages.amitverma.1111111111': info}})
After executing this update on your example document the result is:
{
"_id" : ObjectId("5273d09ab743db7a5f000001"),
"messages" : {
"amitverma" : {
"1111111111" : {
"to" : "...",
"message" : "...",
"sender" : "..."
},
"1383321712" : {
"to" : "macbook",
"message" : "hi.",
"sender" : "amitverma"
},
"1383321755" : {
"to" : "macbook",
"message" : "hi.",
"sender" : "amitverma"
}
}
},
"username" : "macbook"
}
You don't say what kind of queries you want to do, but here's an
example that shows the kind of thing you might do. This query finds a
document with a give username, and uses a projection to return only a
specific subset of the document, in this example the element that we just
added:
c.findOne({username:'macbook'}, {'messages.amitverma.1111111111':1})
This query produces the following result:
{
"_id" : ObjectId("5273d09ab743db7a5f000001"),
"messages" : {
"amitverma" : {
"1111111111" : {
"to" : "...",
"message" : "...",
"sender" : "..."
}
}
}
}
Hope this helps,
Bruce

Categories

Resources