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... :-)
Related
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);
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.
I'd like to set a property to an object using prototype, if it's possible, so that when I try to get an undefined value, it returns a default instead of undefined, like:
obj = {
lang : {en: 'hello', it:'ciao'}
}
Example 1: obj.lang.es (undefined) - I'd like to get obj.lang.en instead of undefined.
Example 2: obj.something.else - I'd like to get false instead of an error because it can't read else of undefined.
It is probably not a good idea.
Better use a root or default key:
obj = {
lang : {root: 'hello', en: 'hello', it:'ciao'}
}
So you can ask for a lang in this way:
var hi = obj.lang.es || obj.lang.root;
You can use this in combination with a getter method:
var getTranslation = function(lang) {
return obj.lang[lang] || obj.lang.root;
};
var hi = getTranslation("es");
This is not a pretty solution, but here it goes, create a prototype object that for any language defers the result to a default language. Then your particular object inherits from that prototype object and overrides any value it wants.
var languages = ['en', 'it', 'es']; // fill with every language you will ever use
var defaultLang = 'en';
var protoLang = Object.create(null);
function getDefaultLanguage(){
return this[defaultLang];
}
languages.forEach(function(language){
Object.defineProperty(protoLang, language, {
get : getDefaultLanguage
});
});
var obj = {
lang : Object.create(protoLang, {
en : { value : 'hello' },
it : { value : 'ciao' }
})
};
obj.lang.es // "hello"
obj.lang.en // "hello"
obj.lang.it // "ciao"
The thing is that you have to define every property first, that is why you need the languages array.
I agree with #DCoder. Maybe something like this:
function getLang(lang) {
var result = this.obj[lang];
if ( typeof result == 'undefined' ) {
result = this.obj.en;
}
return result;
}
You do not need ; inside object, there no content in obj.lang, instead try it like this:
obj = {
lang: {en: 'hello', it: 'ciao'}
};
if (obj.lang.hasOwnProperty("en")) {
console.log(obj.lang.en);
} else {
console.log(false);
}
I have a form with inputs using this naming convetion:
<input class="xxlarge" name="note[url]" id="url" placeholder="URL">
So, I'm using this script (found on StackOverflow) that serializes form data into JSON.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and on the output I have this:
{"note[url]":"URL","note[title]":"TITLE"}
I'd like to know how to transform this script to get output like this:
{"url":"URL","title":"TITLE"}
I'm handling this from with rather standard, documented code block (using function, described above):
$(function() {
$('form').submit(function() {
$('#result').html(JSON.stringify($('form').serializeObject()));
$.post(
"/api/create",
JSON.stringify($('form').serializeObject()),
function(responseText){
$("#result").html(responseText);
},
"html"
);
return false;
});
Thanks in advance!
I would suggest parsing the string into a JS object, changing the keys in a for loop, then stringifying it when you're done. Like so:
// turn the string into a JS object
var data = JSON.parse('{"note[url]":"URL","note[title]":"TITLE"}');
var newData = {};
// step through each member
for(key in data) {
// Regular expressions to find the brackets
var newKeyStart = key.search(/note\[/) + 5;
var newKeyEnd = key.search(/\]/);
// pull out the desired part of the key
var newKey = key.substr(newKeyStart, newKeyEnd - newKeyStart);
// insert into new data object
newData[newKey] = data[key];
}
// turn back into JSON again
var newJSON = JSON.stringify(newData);
Not sure where your 'note' part is coming from. May be something you could fix via the name attributes in your markup. Otherwise you could always do something like:
function renameKeys(obj) {
var
result = {},
key,
check,
noteReg = /^note\[([^\]]+)\]$/;
for(key in obj) {
result[(check = key.match(noteReg)) === null ? key : check[1]] = typeof obj[key] == 'object' && toString.call(obj[key]) == '[object Object]' ? renameKeys(obj[key]) : obj[key];
}
return result;
}
which can be used to make a new object with the keys you want.
renameKeys({"note[url]":"URL","note[title]":"TITLE"});
// { url: 'URL', title: 'TITLE' }
renameKeys({"note[url]":"URL","note[title]":"TITLE", anotherObj: { thingA: 1234, 'note[thingB]': 9492}});
// { url: 'URL', title: 'TITLE', anotherObj: { thingA: 1234, thingB: 9492 } }
Beware, though, that if you have something like a key of note[asdf] and a key of asdf then whichever is iterated over last will overwrite the other.
I have next object:
var myArray = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
Also I have function that returns elements (it's value depends from different conditions):
function getNewElement(condition1, ..., conditionN) {
...
return { "my btn": function() { alert(kkk); } }
}
How I can add to myArray value that returns me getNewElement function?
myArray["fn"] = getNewElement;
Do you mean
myArray["newElement"] = getNewElement();
or
myArray["my btn"] = getNewElement()["my btn"];
?
Another way to create new Objects
var myObj = {
firstName : "Gareth"
lastName : "Simpson"
};
function getNewElement(condition1, ..., conditionN) {
return { "my btn": function() { alert(kkk); } }
}
myObj.getNewElement;
//to call the function
myObj.getNewElement();