I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;
Related
I have List of items data and empty array quotations :
var data = {};
var quotations = [];
I want to fill quotations with data values ,Every time i add new data it added successfully but all data values get last value .
for example :
$("#addquotation").click(function () {
debugger;
var itemname = $("#itemname").val();
var cost =parseFloat( $("#cost").val());
var notes = $("#notes").val();
var date = $("#date").val();
data.Item = itemname;
data.Cost = cost;
data.Notes = notes;
data.Date = date;
quotations.push(data);
)};
for first time i add
"test,45,testnotes,2016-02-03" Second time i 've added
"test2,45.2,testnotes2,2016-02-05"
when i debug i get data as :
obj(0): "test2,45.2,testnotes2,2016-02-05"
obj(1):"test2,45.2,testnotes2,2016-02-05"
it seems it append last version to all data
Please Advice . Thanks
You need to declare data inside the click handler, if it's declared as a global variable you are basically always modifying and adding the same data object to the array:
var quotations = [];
$("#addquotation").click(function () {
debugger;
var data = {};
var itemname = $("#itemname").val();
var cost =parseFloat( $("#cost").val());
var notes = $("#notes").val();
var date = $("#date").val();
data.Item = itemname;
data.Cost = cost;
data.Notes = notes;
data.Date = date;
quotations.push(data);
)};
You are pushing the same object reference each time since you declared data outside of the click handler.
Change from :
var data={};
$("#addquotation").click(function () {
To
$("#addquotation").click(function () {
var data={};// declare local variable
The problem is that data is a global variable and you add a reference to data to quotations.
When the first value is pushed to quotations, data and quotations[0] refer to the same object. Here is an example of what is happening:
var a = {num: 1};
var b = a;
b.num = 2;
console.log(a.num); // prints 2
The same thing happens when an object is pushed to an array. quotations does not contain a copy of data, it contains a reference to data so that modifying data also modifies quotations. To fix this, each element of quotations must refer to a different data object. This can be accomplished by defining data inside of the function instead of outside.
Replace
var data = {};
$("#addquotation").click(function() {
// populate data, push to quotations
});
with
$("#addquotation").click(function() {
var data = {};
// populate data, push to quotations
});
I am new to javascript so i dont know how to create object once we have values dynamically , so below code i have fullName and workerKey from dataItem now i want to create object selectedOwners with values of fullName and workerKey.
How can i achieve that task ?
ctrl.js
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
var fullName = dataItem.fullName;
var workerKey = dataItem.workerKey;
console.log('WORKER KEY', workerKey);
}
You use an object initializer:
selectedOwners = {
fullName: dataItem.fullName,
workerKey: dataItem.workerKey
};
The object initializer is the {...} bit. Each of those two things inside it is a property initializer. The part before the : is the name, the part after is the value, which can be the result of any expression.
In your code, you'd already created the object (var selectedItem = {};). The code above will replace that object. If you just wanted to add to it, you'd just use assignment:
selectedItem.fullName = dataItem.fullName;
selectedItem.workerKey = dataItem.workerKey;
Which you use depends on whether it matters that you not create a new object.
Edited, as per comments:
var list = [];
$scope.addProcessOwner = function(dataItem){
var selectedOwners = {"fullname":dataItem.fullName,"workerKey":dataItem.workerKey};
list.push(selectedOwners);
}
// use list to populate output
You have already created the object so all you need to do is add the values into it.
var selectedOwners = {};
$scope.addProcessOwner = function(dataItem){
selectedOwners.fullName = dataItem.fullName;
selectedOwners.workerKey = dataItem.workerKey;
//This will print out the newly populated object
console.log(selectedOwners);
}
var markerList1={};
var markerList=[];
and adding iterator values from the one for loop
function addSomething() // this function will multiple times from a for loop
{
image ='../css/abc/'+image[iterator]+'.png';
var data = respData[iterator];
var box = getbox(data);
var markerOpts = {
position : coordinates[iterator],
map : map,
icon :image,
title :data[1],
id : data[11]
};
var vmarks = new google.maps.Marker(markerOpts);
markerList.push(vmarks);
markerList1[markerOpts.title].push(vmarks);
}
whenever we call the function i want append the array's values to same index
markerList1[data[11]].push(vmarks);
but i'm not getting above result, when i markerList1[data[11]) then i'm getting only the last value i.e thirdvmark
i want output like this= markerList1[data[11]] = {firstvmark, secondvmark, thirdvmark};
You cannot do push to an object markerList1, only to an array.
change this
markerList1[markerOpts.title].push(vmarks);`
To this
markerList1[markerOpts.title] = vmarks;
markerList1[data[11]] is never initialized before you push something inside.
You can initialize it only once with a simple test:
if (! (data[11] in markerList1) ) {
markerList1[data[11]] = [];
}
markerList1[data[11]].push(vmarks);
Or in a shorter and safer way:
markerList1[data[11]] = markerList1[data[11]] || [];
markerList1[data[11]].push(vmarks);
(And please put data[11] in a variable)
Try this-
var vmarks = new google.maps.Marker(markerOpts);
markerList.push(vmarks);//you already pushing vmarks to array
markerList1[markerOpts.title]=markerList;//assign array to your markerList1 map
I have an array containing 3 elements
var a = [];
a["username"]=$scope.username;
a["phoneNo"]=$scope.phoneNo;
a["altPhoneNo"]=$scope.altPhoneNo;
Now, I want to send this data to server in JSON format. Therefore, I used
var aa = JSON.stringify(a);
console.log("aa = "+aa);
But the console displays empty array
aa = []
How can I convert this array into JSON?
That's not the correct way to add elements to an array, you're adding properties instead.
If you did console.log(a.username); you'd see your $scope.username value.
You could either do
var a = [];
a.push({"username": $scope.username});
a.push({"phoneNo": $scope.phoneNo});
a.push({"altPhoneNo": $scope.altPhoneNo});
But it looks more like what you're trying to do is
var a = {};
a["username"] = $scope.username;
a["phoneNo"] = $scope.phoneNo;
a["altPhoneNo"] = $scope.altPhoneNo;
That is, you want your a to be an object if you're going to add properties to it.
And that would be better written as
var a = {};
a.username = $scope.username;
a.phoneNo = $scope.phoneNo;
a.altPhoneNo = $scope.altPhoneNo;
I want to iterate through a database and store the information as an array or object.
I don't really care which as long as I can store and retrieve based on a key.
I need guidence on the syntax to use to create and store data in javascript
// create storageEntity as array or objects
storageEntity = {};
storageEntity = [];
// on each retreival from data base store data in "storageEntity"
// conceptually it should look like this:
storageEntity[recordIFromFile][recordType][dataType] = value
where:
recordIFromFile - is an numeric value from file
recordType - is a string from file
dataType - is a string from file
value - is a numeric value from the file
You want to use an object/dictionary, i.e.
var storageEntity = {};
If your ID is 99999, you'd need 99998 empty entries in an array, I guess this isn't what you want. Now if you want to store a piece of data:
var record = storageEntity[recordIFromFile];
if (record == undefined) {
record = {};
storageEntity[recordIFromFile] = record;
}
var byType = record[recordType];
if (byType == undefined) {
byType = {};
record[recordType] = byType;
}
byType[dataType] = value;
Why can't you just request a JSON from your server and work over that instead?