Multidimensional array in a object - javascript

I am trying to run following code:
var groupSocketIdList={};
var groupId=5;
if (groupSocketIdList[groupId] == undefined) {
groupSocketIdList[groupId] = [[]];
}
groupSocketIdList[groupId]["tolgay"] = "1234";
var sendData = {
groupPassCode: groupSocketIdList[groupId]
}
console.log(sendData.groupPassCode[groupId]);
It is returning undefined but when I try like this:
console.log(groupSocketIdList[groupId]);
It works well.
How can I prevent from undefined ?

groupSocketIdList[groupId] should be Object
groupSocketIdList[groupId] should be just reference to groupSocketIdList
var groupSocketIdList = {};
var groupId = 5;
if (groupSocketIdList[groupId] == undefined) {
groupSocketIdList[groupId] = {};
}
groupSocketIdList[groupId]["tolgay"] = "1234";
var sendData = {
groupPassCode: groupSocketIdList
}
console.log(sendData.groupPassCode[groupId]);
console.log(sendData.groupPassCode[groupId]['tolgay']);

change this
groupSocketIdList[groupId] = [[]]
to
groupSocketIdList[groupId] = {}
(groupSocketIdList[groupId]["tolgay"] ) this means you are defining a property for groupSocketIdList[groupId] it should be an object but you defined it as a array so thats why you are getting error.

Change Your Last step
console.log(sendData.groupPassCode[groupId]);
to
console.log(sendData.groupPassCode);
You will get all data Of List

You should call like this.
console.log(sendData.groupPassCode['tolgay']);
Because your object is in this format:
{
'sendData': {
'groupPassCode' : [[]]
}
}
your adding property to array not to object.

Related

How do you populate a dynamic variable in AngularJS

The following code gives me the error "Cannot read property PERSON1 of null". If I comment out the line where I try to assign the dynamic variable and uncomment the alert line it pops up alerts with each successive person's name.
function fillInternalRepData() {
var internalRepList = null;
console.log("Querying Table for internal reps");
queryTable(//..blabla..//, "false", function (callbackResp) {
internalRepList = callbackResp;
// alert("TRIGGERED"); //WORKS
// alert(internalRepList.length); //WORKS
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
$scope.internalReps[repName].such = repName;
//alert(repName); //WORKS WHEN LINE ABOVE IS COMMENTED OUT
});
}); //get list of internal reps
I simply want to create/add to the $scope.internalReps object so that I can add stuff to it like $scope.internalReps.PERSON1.Name = "Whatever"; $scope.internalReps.PERSON1.Salary = 100000;
Try adding an empty object for the "internalReps" before your forEach loop. It doesn't look like you've declared the object yet, so it can't dynamically add to a null object.
$scope.internalReps = {};
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
$scope.internalReps[repName] = {};
$scope.internalReps[repName].such = repName;
//alert(repName);
});
var internalReps = {};
angular.forEach(internalRepList, function (rep) {
repName = rep.such;
internalReps[repName] = { such: "" };
internalReps[repName].such = repName;
//alert(internalReps[repName].such);
});
That worked. Thanks for the help!

Object save in same value in angularjs

I am going to push object in an array using angularjs. But it stores same value in every object. Its an associate object.
service('setAttribs',function(){
var setMapAttrib = {
Processtet : {},
};
var tmp = [];
return {
setvalues : function(value){
tmp.push(value);
console.log(tmp);
//setMapAttrib.Processtet[value.SelectedId] = { [value.getIndex] : value };
//setMapAttrib.Processtet[value.SelectedId] = { [value.getIndex] : value };
//console.log(setMapAttrib.Processtet[value.SelectedId]);
/* if(setMapAttrib.Processtet[value.SelectedId]==null)
setMapAttrib.Processtet[value.SelectedId] = [{}];
setMapAttrib.Processtet[value.getIndex] = value;
console.log(setMapAttrib.Processtet); */
},
Anyone has an idea to fix this?
Use angular.copy() to avoid pushing same scope object reference to array over and over
setvalues : function(value){
var newItem = angular.copy(value);
tmp.push(newItem );
console.log(tmp);

unable to change javascript object property with async, nodejs and mongodb

I have the following code:
exports.home = function(Comment,User,Activity){
return function(req, res){
var get_url = req.url.split(/\?/)[1];
if (!req.user)
{
res.writeHead(302, {
'Location': '/'
});
res.end();
return;
}
var posts_id_array = req.user.posts_id_array;
var stocks_array = req.user.watch_list;
var subscribe_to_arr = req.user.subscribe_to;
User.find({_id:{$ne:req.user._id, $nin:subscribe_to_arr}}).sort('-_id').limit(10).exec(function(err_user, users){
Activity.find({$or:[{owner_id : {$in :subscribe_to_arr}},{owner_id:req.user._id}]}).sort('-time_stamp').limit(20).exec(function(err_post,activities){
if( err_post || !activities) {
res.render('home',{user:req.user,stocks:JSON.stringify(stocks_array)});
}
else
{
var funcArr = [];
var hasPost = ["publish","comment","like"];
var notPost = ["add_stock","delete_stock"];
for(var i =0;i<activities.length;i++)
{
if(hasPost.indexOf(activities[i].type)!=-1){
var fobj = {
act: activities[i],
f:function(callback){
var test = this.act;
var comments = test.post.comments;
Comment.find({_id:{$in:comments}},function(err,_comments){
console.log("test.post.comments");
//console.log(test.post.comments);
console.log("comments ");
console.log(_comments);
console.log("type");
console.log(typeof test);
console.log("cloning obj");
// obj = JSON.parse(JSON.stringify(test)); // cloning obj
console.log(test);
console.log("setting value of comments");
**console.log(test.post.comments = _comments);** //unable to change test.post.comments
console.log("after assignment");
console.log(test.post.comments); // remain unchanged but work with obj.post.comments if I clone test as obj and use obj instead.
callback(null,test);
});
}
}
funcArr.push(fobj.f.bind(fobj));
}else{
var fobj = {
act: activities[i],
f :function(callback){
callback(null,this.act);
}
}
funcArr.push(fobj.f.bind(fobj));
}
}
async.series(funcArr,function(err,resArr){
console.log("resArr");
console.log(resArr);
res.render('home',{user:req.user,posts:JSON.stringify(resArr),stocks:JSON.stringify(stocks_array), other_users:JSON.stringify(users)});
});
}
});
}) // end of User.find
}// end of return function(req,res);
}
I want to update the post.comments property of the "test" object (see ** parts), but I was unable to do so. However, when I cloned the "test" object as "obj" then set "obj.post.comments" it works. Why is it the case? Is it because I messed up some scoping issues?
Thanks.
I have solved this problem myself. It turns out that I have store mongodb's Schema.Types.ObjectId in the test.post.comments which after some messing around I found cannot be overwritten. When I create a clone of the test object as "obj", the Schema.Types.ObjectId object in obj.post.comments is stored at a different location which allows for modification. My conjecture is that test.post.comments points to a Schema.Types.ObjectId within mongodb itself and therefore cannot be overwritten. When I create a copy of the test object, the problem is therefore resolved.
var test = this.act.concat();
use this instead.
because arrays substitution in js actually does not copy array but refer original adresses.
for example
var test = ['A','B','C','D'];
var copied = test;
test[0] = 0;
copied[1] = 0;
console.log(test) //0,0,'C','D'
console.log(copied) //0,0,'C','D'
so to avoid this issue, You can use .concat() to copy array
if you do not add anything, it will be used as copying.
var test = ['A','B','C','D'];
var copied = test.concat();
test[0] = 0;
copied[1] = 0;
console.log(test) //0,'B','C','D'
console.log(copied) //'A',0,'C','D'

How to put object in a HashMap in js?

I create Simple HashMap like this , but When I put an object into this map as a value, I can't call object's function when I get it from map , I find that the object was convert to string by toString function. So what should I do to put the object itself rather than a string into map?
var g_itemMap =
{
put : function(key,value){this[key] = value},
get : function(key){return this[key]},
contains : function(key){return this.get(key) == null?false:true},
remove : function(key){delete this[key]}
}
I put the object like this:
g_itemMap.put(1, object);
And get it:
var object = g_itemMap.get(1);
When I call it's function , it went wrong:
object.somefunction();
alert can display object:
[object BitmapItem]
This code looks like working for me.
You can try this;
var g_itemMap =
{
put : function(key,value){this[key] = value},
get : function(key){return this[key]},
contains : function(key){return this.get(key) == null?false:true},
remove : function(key){delete this[key]}
}
var object =
{
objectfunction: function(){
console.log('objectfunction called')
}
}
g_itemMap.put(1, object);
var o = g_itemMap.get(1);
o.objectfunction();
Fiddle link: http://jsfiddle.net/hCH8k/
var HashMap = new Object();
HashMap[Key1] = Obj1;
HashMap[Key2] = Obj2;
function get(k)
{
console.log(HashMap[k]);
}
or simply you can use
var HashMap = {"Key1":"value1","Key2":"value2"}
function get(k)
{
console.log(HashMap[k]);
}
If I try
var object = { a: function() { alert('b'); } };
var g_itemMap =
{
put : function(key,value){this[key] = value},
get : function(key){return this[key]},
contains : function(key){return this.get(key) == null?false:true},
remove : function(key){delete this[key]}
}
g_itemMap.put(1, object);
var object2 = g_itemMap.get(1);
object2.a();
does alert('b'), which looks correct, to me... :-)

Setting array in javascript

Noob question. Setting array elements throws an error.
I get this error when I run the script: array1[user_id] is undefined.
array1 = new Array();
// the data variable I got from a JSON source
// using jQuery
$.each(data, function(i, item) {
// Set variables
user_id = item.post.user_id;
user = item.post.user;
price = item.post.price;
if (array1[user_id]['user'] != user) {
array1[user_id]['price'] = price;
array1[user_id]['user'] = user;
}
}
First, you should not use an array, if you need a hash map, use objects. In some languages, it's one thing, but in JS they're not.
When defining a nested object you have to define each level as an object.
var hash = {};
// the data variable I got from a JSON source
$.each(data, function(i, item) {
// Set variables
user_id = item.post.user_id;
user = item.post.user;
price = item.post.price;
// Have to define the nested object
if ( !hash[user_id] ) {
hash[user_id] = {};
}
if (hash[user_id]['user'] != user) {
hash[user_id]['price'] = price;
hash[user_id]['user'] = user;
}
}
If I understand this question correctly, you have to initialize the first dimension of array1 first, like so:
array1[user_id] = {};
then you can do this:
array1[user_id]['user'] = 'whatever';
That is of course assuming your user_id is not undefined.

Categories