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);
});
Related
hope you are doing well. I have faced an issue. I'm creating a dynamic array but when I console that variable and check typeOf of this variable it showing an object instead of an array. Also when I access a specific element of that variable it's showing undefined. Let me know how can I resolve this issue. you can check I have declared a global variable name of test and push data in it. it should return an array because I'm pushing it in the array. But showing object.
$(document).ready(async function(){
await load_pre_data(true);
});
let pre_data= [];
let count = 1;
var test = [];
let ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=1089');
async function load_pre_data() {
ws.onopen = function (evt) {
ws.send(JSON.stringify({
ticks_history: 'frxAUDJPY',
adjust_start_time: 1,
count: 5,
end: "latest",
start: 1,
style: "ticks"
}));
};
ws.onmessage = function (msg) {
let response = JSON.parse(msg.data);
let loop;
for (loop = 0; loop <= response.history.prices.length; loop++) {
test.push(1);
}
}
console.log(test);
console.log(typeof (test));
}
In Javascript every array is the type of an object and for your typechecking you can use "Array.isArray(test)".
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
You can read about isArray() method here
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 have the following type of structure:
(function(){
var objects = [];
$('button.one').on('click', function(){
fetchObjects = function(objects) {
$.post("/fetchObjects")
.done(function(data){
objects = data;
console.log(objects.length);
});
}
fetchObjects(objects)
});
$('button.two').on('click', function(){
console.log(objects.length);
});
})();
You can see I have a variable objects that is local to this function. Initially its empty. When I click button.one I wish to populate objects with the returned value from some ajax request. It appears to work, however when clicking button.two, the objects variable is still an empty array.
Why isn't objects available in the jQuery callback?
I've also tried this approach but with the same results:
function callback(data) {
facilities = data
}
$.post("/fetchObjects")
.done(function(data){
callback(data);
});
What am I missing here? Please don't tell me to make "objects" global.
I don't know why you're passing objects as parameter. The following should work fine I think. Please let me know if you're trying to achieve something else.
(function(){
var objects = [];
$('button.one').on('click', function(){
fetchObjects = function() {
$.post("/fetchObjects")
.done(function(data){
objects = data;
console.log(objects.length);
});
}
fetchObjects()
});
$('button.two').on('click', function(){
console.log(objects.length);
});
})();
Let's simplify the code a bit. You have essentially this:
var objects = [];
fetchObjects = function(innerObjects) {
var data = ['a','b'];
innerObjects = data;
console.log(innerObjects.length);
};
fetchObjects(objects);
console.log(objects);
(I've changed the other objects variable's name just for clarity; the issue is the same even if it had the same name.)
When you call the function, innerObjects contains a reference to objects so modifying it would change the original array as well. But when you do
innerObjects = data;
now instead of modifying the array you're replacing the reference with something else. innerObjects "points" to data instead of objects and the original variable remains unchanged.
To make it work you'd need to loop through the data array (assuming it'll always be an array) and assign the contents to the objects reference one by one. This way you'll keep the original reference and modify the original array.
var objects = [];
fetchObjects = function(innerObjects) {
var data = ['a','b'];
for( var i = 0; i < data.length; i++ ) {
innerObjects[i] = data[i];
}
console.log(innerObjects.length);
};
fetchObjects(objects);
console.log(objects);
Or, in your actual code:
(function(){
var objects = [];
$('button.one').on('click', function(){
fetchObjects = function(objects) {
$.post("/fetchObjects")
.done(function(data){
for( var i = 0; i < data.length; i++ ) {
objects[i] = data[i];
}
console.log(objects.length);
});
}
fetchObjects(objects)
});
$('button.two').on('click', function(){
console.log(objects.length);
});
})();
Here is the code:
http://jsfiddle.net/GKBfL/
I am trying to get collection.prototype.add to return a reference such that the final alert will display testing, testing, 123, testing. Is there a way to accomplish what I'm trying to do here?
HTML:
<span id="spantest">testing, testing, 123, testing</span>
JavaScript:
var collection = function () {
this.items = {};
}
collection.prototype.add = function(sElmtId) {
this.items[sElmtId] = {};
return this.items[sElmtId];
}
collection.prototype.bind = function() {
for (var sElmtId in this.items) {
this.items[sElmtId] = document.getElementById(sElmtId);
}
}
var col = new collection();
var obj = {};
obj = col.add('spantest');
col.bind();
alert(obj.innerHTML);
You problem is this line:
this.items[sElmtId] = document.getElementById(sElmtId);
This overwrites the object currently assigned to this.items[sElmtId] with the DOM node. Instead, you should assign the node to a property of that object:
this.items[sElmtId].node = document.getElementById(sElmtId);
That way, obj.node will always refer to the current node:
alert(obj.node.innerHTML);
DEMO
Side note: The problem with your fiddle is also that you execute the code when the DOM is not built yet (no wrap (head)), so it cannot find #spantest. You have to run the code once the DOM is ready, either no wrap (body), onDomRead or onLoad.
Creating a reference like you need is impossible in JavaScript. The closest thing you can get is either a nested or closed object, or just copying it over, like so:
var collection = function() {
this.items = {};
};
collection.prototype.add = function(sElmtId) {
return this.items[sElmtId] = {};
};
collection.prototype.bind = function() {
for(var sElmtId in this.items) {
var element = document.getElementById(sElmtId);
for(var x in element) {
this.items[sElmtId][x] = element[x];
}
}
};
var col = new collection();
var obj = {};
obj = col.add('spantest');
col.bind();
alert(obj.innerHTML);
But it won't be truly "bound". You'll have to use nested objects if you need that kind of functionality, and it will probably defeat the point of your syntactic sugar.
http://jsfiddle.net/GKBfL/7/
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.