Object save in same value in angularjs - javascript

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);

Related

Create multidimensional javascript object from values in array using jquery .each loop

I need to create a javascript object using values stored in an array. Every value should be a new key inside the previous one. What would be the best approach to achieve this?
var option = ['level_1','level_2','level_3','level_4'];
$.each( option, function( key, value ) {
// ....
});
// I'm trying to get this result
var result = {
'level_1': {
'level_2': {
'level_3': {
'level_4':{}
}
}
}
}
You can use reduceRight for this, with the ES6 computed property name syntax.
const option = ['level_1','level_2','level_3','level_4'];
const obj = option.reduceRight( (acc, lvl) => ({ [lvl]: acc }), {});
console.log(obj);
In traditional function syntax it would be:
const obj = option.reduceRight(function (acc, lvl) {
return { [lvl]: acc };
}, {});
You have to keep track of where to put the next key. So, create a variable and initially set it to result, then on each pass through the array, move where that variable points to.
var option = ['level_1','level_2','level_3','level_4'];
var result = {};
var nextKeyGoesHere = result;
option.forEach( function( value ) {
nextKeyGoesHere[value] = {};
nextKeyGoesHere = nextKeyGoesHere[value];
});
console.log(result);
Can use Array#reduce()
var option = ['level_1','level_2','level_3','level_4'];
var res = {};
option.reduce((o, key) => (o[key] = {} , o[key]), res)
console.log(res)
you can use any of the other answers that use Array#reduce, however, if you'd like a recursive version here it is:
function _makeTree(arr, index, subtree){
if(index < arr.length){
subtree[arr[index]] = {};
return _makeTree(arr, index+1, subtree[arr[index]])
}
else return;
}
function makeTree(arr){
var tree = {};
_makeTree(arr, 0, tree)
return tree;
}
var arr = ['level_1','level_2','level_3','level_4'];
console.log(makeTree(arr));

Save key=>value style with ngStorage/localstorage

In my Ionic app I've added the plugin 'ngStorage' and it comes with a little demo code:
var add = function (thing) {
$localStorage.things.push(thing);
}
This works exactly as told. I add("foo") it, and do getAll() and the value is there. I remove the add(), but keep the getAll(), I still have the value "foo" (as expected).
This isn't very usefull for me, I want to access it with keys, so I've made the following:
var addByKey = function (key, value) {
$localStorage.things[key] = value;
// Or, I've also tried:
$localStorage.things.key = value;
}
When I do the addByKey("foo","bar") and then the getAll() I get the values exactly as I want. When I remove the addByKey() and reload, I expect it to still remember the set information, but it doesn't exist. However, the first attempt via the add() function still exists, "foo" is still there (meaning the array doesnt reset).
How do I make a key->value type of structure?
In case it's usefull:
.factory ('StorageService', function ($localStorage) {
$localStorage = $localStorage.$default({
things: []
});
var _getAll = function () {
return $localStorage.things;
};
var _add = function (thing) {
$localStorage.things.push(thing);
}
var _addByKey = function (thing, value) {
$localStorage.things[key] = value;
// Or, I've also tried:
$localStorage.things.key = value;
}
return {
getAll: _getAll,
add: _add,
addByKey: _addByKey
};
})
Assuming that you want a key value storage system you can simply use an object instead of an array so that every key can be set as a property of this object.
.factory('StorageService', function($localStorage) {
$localStorage = $localStorage.$default({
things: {}
});
var _getAll = function() {
return $localStorage.things;
};
var _addByKey = function(thing, value) {
$localStorage.things[thing] = value;
}
return {
getAll: _getAll,
addByKey: _addByKey
};
})
However, assuming that you want to keep a reference of all values on the main collection and access them through keys, you can consider using an object to store the things intead of an array. So that you can use a property to store all items (you can store in a different place as well) and use this object to store your keys by referencing the to a desired value on your collection.
You may need to implement the deletion logic to maintain the consistence between the collection and the dictionary.
Your factory would look like this:
.factory('StorageService', function($localStorage) {
$localStorage = $localStorage.$default({
things: {
items: []
}
});
var _getAll = function() {
return $localStorage.things.items;
};
var _add = function(thing) {
$localStorage.things.items.push(thing);
}
var _addByKey = function(thing, value) {
var i = $localStorage.things.items.push(value) - 1;
$localStorage.things[thing] = $localStorage.things.items[i];
}
return {
getAll: _getAll,
add: _add,
addByKey: _addByKey
};
})

Multidimensional array in a object

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.

Creating an object from html elements using JavaScript and jQuery

I want to create an object from html elements using JavaScript and jQuery.
The object i want to create is
{
array:[{infraStructureType: 'value', hostId: 'value'}, {infraStructureType: 'value', hostId: 'value'}]
}
So my code to create above object is
var obj = {}, dataObj = {compareESX: []};
$('.checkBox:checked').each(function () {
obj.infraStructureType = $(event.target).attr('hostId');
obj.hostId = $(event.target).attr('infrastructureType');
console.log(obj);
dataObj.compareESX.push(obj);
console.log(dataObj);
});
In above code "console.log(obj)" gives correct output but, when i push it in array "dataObj.compareESX"
Only information of last 'obj' is getting pushed number of times the each loop executes.
JS uses Call by reference method.So when update obj it changes all values. You need to do deep copy.Use this
dataObj.compareESX.push(JSON.parse(JSON.stringify(obj)));
Try this: FIDDLE
We need to define the obj again to clear the previous values.
var dataObj = {compareESX: []};
$('.checkBox:checked').each(function (e) {
var obj = {};
obj.infraStructureType = $(this).attr('hostId');
obj.hostId = $(this).attr('infrastructureType');
//console.log(obj);
dataObj.compareESX.push(obj);
//console.log(dataObj);
});
console.log(dataObj);
You have to put your object definitions var obj = {} inside your each loop. Right now you are using the same object for every entry in the loop. Instead, you should create a new object for every checkbox over which you loop.
var dataObj = {compareESX: []};
$('.checkBox:checked').each(function () {
var obj = {};
obj.infraStructureType = $(event.target).attr('hostId');
obj.hostId = $(event.target).attr('infrastructureType');
console.log(obj);
dataObj.compareESX.push(obj);
console.log(dataObj);
});

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... :-)

Categories