Javascript multidimensional object overwriting last inserted item - javascript

I am trying to get a MD object in javascript, I have something this at the moment, but it isn't exactly what I want:
{"usernames":["Ted","Mikey"],"room_status":[0,0]}
The idea is that I want the room status values of 0 assigned to Ted and Mikey at the moment they are not. So I can then use:
$.each(usernames, function(index, value){
//do stuff
})
... to loop through the names and see which room status value is assigned to who.. I also tried something along the lines of this:
usernames = {
'username' : {
'username' : username,
'room_status' : 0
}
}
which returns:
{"username":{"username":"asdfgasdc","room_status":0}}
but overwrites the last item...

var users = [{
username: 'Ted',
room_status: 0
}, {
username: 'Mikey',
room_status: 0
}];
This gives you an array of objects, which you can either loop or access directly
$.each(users, function(index, user){
console.log(user.username + ' - ' + user.room_status);
});
// Ted - 0
// Mikey - 0
var user = users[0];
console.log(user.username + ' - ' + user.room_status);
// Ted - 0

You could easily use the usernames as keys:
var people = {
Mike: { room_status: 0 },
Ted: { room_status: 0 }
}
And loop through them with a for loop:
for(var person in people){
people[person].room_status
}
And even access them directly:
people.Mike.room_status
It would be more recommended to syphon everyone into a prototype and assign that to the username, as that way you can easily check for normals in your for loop (aka if( people[person] instanceof Person ) // run code, ignoring any possible default functions or prototype functions that may exist for an object.

change this
usernames = {
'username' : {
'username' : username,
'room_status' : 0
}
}
to
usernames[username] = {
'username' : username,
'room_status' : 0
}
Because the 'username' key will be overwritten for every loop
var usernames = {};
var usernamesList = ["Ted","Mikey"];
for(var i=0;i < usernamesList.length;i++){
var username = usernamesList[i];
usernames[username] = {
'username' : username,
'room_status' : 0
}
}
will give you
usernames : {
Ted:{username:'Ted',room_status:0},
Mikey:{username:'Mikey',room_status:0}
}
calling:
usernames['Ted'].room_status OR usernames.Ted.room_status will return 0

Related

Pouchdb join / link documents

I have pouchdb/couchbase data with equipment that has user assigned to them.
Equipment with _id and in the equipment doc there is a checkedOutBy with the user._id as the value. Within the employee object there is user.name. When I get the equipment objects how do I also get the user.name and display with the equipment.
I have searched and read about map/reduce that uses emit and do not grasp the idea. My code that i wrote from what i learned is:
by the way I am also using Angularjs.
field = "eq::"
this.getAllEquip = function(field){
function map(doc) {
if (doc.checkedOutBy !== undefined) {
emit(doc.checkedOutBy, {empName : doc.name});
}
}
var result = database.query(map, {include_docs: true,
attachments: true,
startkey: field,
endkey: field + '\uffff'})
.catch(function (err) {
//error stuff here
});
return result
};
I don't see where the two docs would get together. What am i missing? My result is empty.
The equipment json looks like:
{checkedOutBy: "us::10015", description: "3P Microsoft Surface w/stylus & power cord", equipId: "SUR1501", purchaseDate: "", rCost: 1000, id:"eq::10001"}
Emlpoyee json:
{"firstname":"Joe","gender":"male","lastname":"Blow","status":"active","title":"office","type":"userInfo","_id":"us::10015","_rev":"2-95e9f34784094104ad24bbf2894ae786"}
Thank you for your help.
Something like this should work, if I understood the question correctly:
//Sample Array of Objects with Equipment
var arr1=[{checkedout:"abc1",desc:"item1",id:1},
{checkedout:"abc2",desc:"item2",id:2},
{checkedout:"abc3",desc:"item3",id:3},
{checkedout:"abc1",desc:"item1",id:4},
{checkedout:"abc4",desc:"item3",id:5},
{checkedout:"abc6",desc:"item3",id:6}];
//Sample array of objects with Employee - the "id" in arr2 matches with "checkout" in arr1
var arr2=[{name:"john",id:"abc1"},
{name:"jack",id:"abc2"},
{name:"alice",id:"abc3"},
{name:"james",id:"abc4"}];
var result = []; //final result array
//loop through equipment array arr1
arr1.forEach(function(obj) {
var tempObj = obj;
var checkedout_id=obj.checkedout;
//do array.find which will return the first element in the array which satisfies the given function. This is absed on the assumption that that the id is unique for employee and there wont bwe multiple employees with same id (which is the "checkedout" field in equipment. If the employee is not found, it will return undefined.
var foundname = arr2.find(function(obj) {
if (obj.id == checkedout_id)
return obj.name
})
//Create the object to be inserted into the final array by adding a new key called "name", based on the result of above find function
if (foundname != undefined) {
tempObj.name=foundname.name
}
else {
tempObj.name = "Not found";
}
result.push(tempObj);
})
This is my Pouchdb solution, thank you Vijay for leading me to this solution.
First I get all my equipment. Then I use Vijay's idea to loop through the array and add the name to the object and build new array. I found there is a need to go into the .doc. part of the object as in obj.doc.checkedOutBy and tempObj.doc.name to get the job done.
$pouchDB.getAllDocs('eq::').then(function(udata){
var result = [];
//loop through equipment array
udata.rows.forEach(function(obj) {
var tempObj = obj;
var checkedout_id=obj.doc.checkedOutBy;
if (checkedout_id != undefined) {
$pouchDB.get(checkedout_id).then(function(emp){
return emp.firstname + " " + emp.lastname
}).then(function(name){
tempObj.doc.name = name;
});
}
result.push(tempObj);
})
in my service I have:
this.get = function(documentId) {
return database.get(documentId);
};
and:
this.getAllDocs = function(field){
return database.allDocs({
include_docs: true,
attachments: true,
startkey: field,
endkey: field + '\uffff'});
};

Create or Update cookie array in Jquery

I want to create if the value is 0 and update if the value is 1.
So I wrote this one,
var juiceCart = [{
'name': val,
'count': unTouch
}];
if (value == 0) {
console.log('create cookie');
$.cookie("juiceCart", JSON.stringify(juiceCart));
doDummyCall();
} else {
console.log('update cookie');
$.cookie("juiceCart", JSON.stringify(juiceCart));
doDummyCall();
}
Inside the doDummyCall()
I am just doing a ajax call to update the headers and
var cookieJuiceCart = $.parseJSON($.cookie("juiceCart"));
$.each(cookieJuiceCart, function (index, value) {
console.log('Id : ' + value.name);
console.log('Value : ' + value.count);
});
and then printing the cookie in each function to know all the items present in it.
If i add the first item, it is printing
Id : 1
Value : 1
Then, if i add the Second item it is printing
Id : 2
Value : 1
But what i expect is
Id : 1
Value : 1
Id : 2
Value : 1
I know that the old value is replaced because i am not pushing the value in it.
So, I did
juiceCart.push({'name': val, 'count': unTouch});
But it is just replacing the old value with new one.
How can i check the existence of old value inside the array and create or update according to it.
The actual problem seems to me is your array:
var juiceCart = [{
'name': val,
'count': unTouch
}];
which is using vars to update same object instead of pushing new object.
You can do this:
var juiceCart = $.parseJSON($.cookie("juiceCart")) || []; // create a blank array taken from #apokryfos's answer.
juiceCart.push({'name': val, 'count': unTouch}); // <---now push it here.
This way you are able to push new object each time you call it.
This is what I got from the question. It's a bit poorly explained so I may not have understood what you need to do.
var juiceCart = $.parseJSON($.cookie("juiceCart")) || [];
var newItem = true;
juiceCart.each(function (i, v) {
if (v.name == val) { v.count++; newItem = false; }
});
if (newItem) {
juiceCart.push({'name': val, 'count': unTouch});
}
$.cookie("juiceCart", JSON.stringify(juiceCart));
doDummyCall();

Appending to JS object

Hope this isn't too much of a repeating question, I've checked around seen similar but can't seem to solve my issue.
I have a JS object:
var option1Data = {
option: 'Yes',
numberOfPeople: 3,
gender: {} ,
region: {}
};
I want to check if an item is in gender, if not add and set to 1 else increment into. Note that appending it in is important.
Can someone kindly tell me whats wrong:
var input = 'female'; //for purposes of this example
var processGender = function(input) {
if(option1Data['gender'].hasOwnProperty(input)) {
option1Data['gender'][input]++;
}else {
option1Data['gender'][input] = 1;
}
};
User.find({_id: item['userID']}, {gender: 1, country:1}, function(req, foundUser) {
processGender(foundUser[0]['gender']);
});
You can't guarantee property order if using an object, you can see this stackoverflow answer for that :
Does JavaScript Guarantee Object Property Order?
So appending is out of the question for the structure you're using.
But maybe something like below would work for you :
var maleGenderObject= { gender : "male" , count : 0 };
var femaleGenderObject = {gender : "female" , count : 0 };
var option1Data = { option: 'Yes',
numberOfPeople: 3,
gender: [] ,
region: {} };
Then when adding , you can do something like :
var input = "female";
//Nothing exists at the moment, so add the proper object, I added both since there are only two, but you can modify for more genders, but logic will be a bit more complex
if ( option1Data.gender.length == 0 ){
if (input == "female" ){
option1Data.gender.push(femaleGenderObject);
option1Data.gender.push(maleGenderObject);
}
else {
option1Data.gender.push(maleGenderObject);
option1Data.gender.push(femaleGenderObject);
}
}
//If both gender objects exist, determine which one you want, and increment its count
if (option1Data.gender[0].gender == input){
option1Data.gender[0].gender.count++;
}
else {
option1Data.gender[1].gender.count++;
}
This definitely can be optimized, but it's really two variables so I think simple straightforward is better in this case
Another way is to have your gender objects have an order property, and you can use that.
Your code is working fine:
var option1Data = {
option: 'Yes',
numberOfPeople: 3,
gender: {},
region: {}
},
input = 'female';
if (option1Data['gender'].hasOwnProperty(input)) {
option1Data['gender'][input]++;
} else {
option1Data['gender'][input] = 1;
}
document.write('<pre>' + JSON.stringify(option1Data, 0, 4) + '</pre>');

How to update multiple collection keys received as arguments?

I'm trying to increase different values in my collection using the same code.
I'm trying to compute that in a function where the updated properties will depend on the parameters:
BuyEntitee : function(id_fb,entitee)
{
var j = Joueur.findOne({id_fb:id_fb});
var prix_current = j["prix_"+entitee];
var update_query = {};
update_query[entitee+"s"] = j[entitee+"s"] + 1;
update_query["prix_"+entitee] = Math.round(50*Math.pow(1.1,j[entitee+"s"]));
Joueur.update( {id_fb:id_fb}, {
$set: {update_query}
}
);
j = Joueur.findOne({id_fb:id_fb}); // on recharge le jouer ... utile ??
console.log('nbHumains : ' + j.humains+ ' query = '+JSON.stringify(update_query));
return j.rochers;
}
But unfortunately, the query is 1 level too deep in the structure :
meteor:PRIMARY> db.joueur.findOne()
{
"_id" :
"humains" : 12,
"prix_humain" : 50,
"update_query" :
{
"humains" : 13,
"prix_humain" : 157
}
}
I'm creating the update_query object so that I can programmatically change the parameters in the update function (saw this here).
Is there a way to perform that?
What happened is, in fact, a result of the ES6 syntactic sugar for specifying objects.
When you specified {update_query}, it was interpreted as an object with the key of "update_query" and the value of the variable update_query.
Therefore, it is the equivalent of:
Joueur.update( {id_fb:id_fb}, {
$set: {
update_query: update_query
}
}
);
What you really want is to assign the update_query itself to the $set key:
Joueur.update( {id_fb:id_fb}, {
$set: update_query
}
);
On a side note, you probably want to use the $inc modifier in order to increment the entitee+"s" by 1.

Issue Pushing values in to objects Javascript

Have some issue with push the values in to the javascript array object. Please any one give me the perfect solution
Class code :
var myfuns = ( function(undefined) {
var myarr ={};
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
}
}
function _getList() {
return $.extend(true, {}, myarr);
}
return {
add : _add,
getList : _getList
}
}());
Here am calling and manage the values and keys
function setmydetails(){
var my_param = {
current_info : {
pg : '#tset',
no : 12,
name : "john",
row : 0,
},
userprofile : [],
class : [],
marks : [],
games : []
};
myfuns.add(my_param);
}
Now i got the array
myfuns.getList() // GOT proper array what i passed in my_param
Question : How to modify the existing values from any one of the Inner array from the myarr Obj
Ex: Once First array created later have to modify some from "myarr.current" = > Change current_info.row to 2222
Similar i have to add some array in to " myarr.class " etc
I would like to say try this one not tested
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
$.extend( myarr.current, arrayparam);
}
}
proper source : https://api.jquery.com/jquery.extend/

Categories

Resources