Create Dynamic Object Javascript - javascript

i just wanted to create a Dynamic Object in JS, but the Object only saves the last Element of the foor loop. Heres my Code :
for(var i = 0; i < req.session.userObjekt.length; i++) {
var userObjekt = {
[req.session.userObjekt[i].User]: {
Data : req.session.userObjekt[i].Data,
Admin: req.session.userObjekt[i].Admin
}
};
}
When i output in the for loop i get the correct result (7 Users + Properties)
When i output out of the for loop, i only get the last User + Properties.
How to save all Elements from the for loop in my Object?
Thanks in advance.

Because you assign to your userObjekt a new object in each iteration. Move out your object declaration from the for loop body
var userObjekt = { };
for(var i = 0; i < req.session.userObjekt.length; i++) {
userObjekt[req.session.userObjekt[i].User] = {
Data : req.session.userObjekt[i].Data,
Admin: req.session.userObjekt[i].Admin
};
}

You can create an array outside of loop and just push the objects in it later on you can use the declared and filled array:
var objektArr = [];
for(var i=0; i<req.session.userObjekt.length; i++) {
var userObjekt = {
[req.session.userObjekt[i].User]: {
Data : req.session.userObjekt[i].Data,
Admin: req.session.userObjekt[i].Admin
},
};
objektArr.push(userObjekt);
}
console.log(objektArr);

Related

Issue populating an array of objects dynamically in javascript

I am facing an issue when populating an array of the object dynamically in javascript. I have this sample data as below:
I have to populate following arrays with the data from above:
c1_Arr = [];
c2_Arr = [];
var torontoObj = { arName: 'تورونتو', enName: 'Totonto', value: 0 };
var parisObj = { arName: 'باريس', enName: 'Paris', value: 0 };
var londonObj = { arName: 'لندن', enName: 'London', value: 0 };
Now I am looping through the data to set the values from data as:
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
var data = results.features[i].attributes;
parisObj.value = data.Paris;
londonObj.value = data.London;
torontoObj.value = data.Toronto;
if (data.Ind_ID === 101) {
c1_Arr.push(parisObj);
c1_Arr.push(londonObj);
c1_Arr.push(torontoObj);
}
}
console.log(c1_Arr);
I am getting this data in console:
Here I am getting the values of the object i.e. Ind_ID = 102 instead of the object values of Ind_ID = 101 (first object).
How to get the values of the required object using the Ind_ID?
The problem is because even though you have the if condition there but you are updating the value of the objects in the loop and since you have already pushed them objects you still have the reference in the main objects. They get overwritten.
Create the 3 objects (torontoObj, etc.) inside the loop.
Reference is getting updated in the second iteration (where Ind_ID is 102)
You should rather do
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
var data = results.features[i].attributes;
if (data.Ind_ID === 101) {
parisObj.value = data.Paris;
londonObj.value = data.London;
torontoObj.value = data.Toronto;
c1_Arr.push(parisObj);
c1_Arr.push(londonObj);
c1_Arr.push(torontoObj);
}
}
console.log(c1_Arr);
Your object values are getting updated even after being set inside the if loop, simply because, you're not limiting it from being updated.
You could probably do one of the following 2 things:
The simpler one:
Extract the values of Paris, London and Toronto fields of data only if the Ind
_ID is 101.
like this:
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
var data = results.features[i].attributes;
if (data.Ind_ID === 101) {
parisObj.value = data.Paris;
londonObj.value = data.London;
torontoObj.value = data.Toronto;
c1_Arr.push(parisObj);
c1_Arr.push(londonObj);
c1_Arr.push(torontoObj);
}
}
console.log(c1_Arr);
The more elegant one:
Extract the array element which only matches your condition, in other words filter.
var resultCount = results.features.length;
var data = results.features.filter(feature => feature.attributes.Ind_ID === 101);
parisObj.value = data[0].Paris;
londonObj.value = data[0].London;
torontoObj.value = data[0].Toronto;
console.log(c1_Arr);

How to iterate over an array in an array

I want to iterate over my 'areasarray' in the array 'areas' dataprovider array,
I have no idea how to loop over an array in an array, I've tried several tries with for-loops but none of it succeeded.
this is amCharts Maps framework.
var areasarray = {};
//get JSON File
$(function getData() {
var url = "../assets/document.json";
$.ajax({
url: url,
dataType: 'json',
success: function (data) {
console.log(data);
for (var i = 0; i < data.fact.length; i++) {
if (inverseCountryCodes[data.fact[i].dims.COUNTRY] != null) {
areasarray[i] = {
"id": inverseCountryCodes[data.fact[i].dims.COUNTRY],
"value": data.fact[i].Value,
"info": "Verkeersdoden per 100 000 inwoners: " + data.fact[i].Value
}
}
}
//console.log(areasarray);
//Map initialiseren
var map;
map = new AmCharts.AmMap();
map.colorSteps = 20;
var dataProvider =
{
mapVar: AmCharts.maps.worldLow
areas: [
{
id: "BE",
value: 10,
info: "Verkeersdoden ..."
}
]
};
console.log(dataProvider);
map.areasSettings = {
autoZoom: true,
selectedColor: "#338DAB"
};
map.dataProvider = dataProvider;
var valueLegend = new AmCharts.ValueLegend();
valueLegend.right = 10;
valueLegend.minValue = "little";
valueLegend.maxValue = "a lot!";
map.valueLegend = valueLegend;
map.addListener("clickMapObject", function (event) {
document.getElementById("info").innerHTML = '<p><b>' + event.mapObject.title + '</b></p><p>' + event.mapObject.info + '</p>';
});
map.mouseWheelZoomEnabled = true;
map.write("mapdiv");
}
});
});
If you want to iterate over areasarray which is actually an object and not an array you should look into using a for...in loop
For iterating over arrays within arrays, one approach would be to nest for loops
for(var i = 0; i < array1.length; i++) {
for(var j = 0; j < array2.length; j++) {
// do something
}
}
It's not clear to me what you mean by "array in an array" in this context and it would help if you provided more information about what exactly you are trying to accomplish
I would try a nested loop. Here is an example of creating an array of arrays and then looping through each.
var matrix = []
matrix[1] = []
matrix[1][1] = "foo"
matrix.forEach(function(column){
column.forEach(function(cell){
console.log(cell);
});
});
var areasarray = {}; means it's an object, not an array.
To iterate through each items in this object, try this.
var keys = Object.keys(areasarray);
keys.forEach(function(k) {
// you can access your item using
// k is the property key
console.log(areasarray[k]);
console.log(areasarray[k].id);
console.log(areasarray[k].value);
console.log(areasarray[k].info);
});
Not sure why you chose to create areasarray as an object.
If you wanted to, you could have defined it as:
var areasarray = [];
Then when adding to the array you use:
areasarray.push({
"id": inverseCountryCodes[data.fact[i].dims.COUNTRY],
"value": data.fact[i].Value,
"info": "Verkeersdoden per 100 000 inwoners: " + data.fact[i].Value
});
So later on, you can simply do:
for (var i = 0; i < areasarray.length; i++) {
console.log(areasarray[i]);
console.log(areasarray[i].id);
console.log(areasarray[i].value);
console.log(areasarray[i].info);
}
Note: in the above code, i is an index, where in the object block code, k is a key to the object.
Use nested loops.
Example:
var a1=["1","2","3","4","5","6","7"];
var a2=["a","b","c","d","e"];
for(var i=0;i<a1.length;i++) //loop1
{
console.log(a1[i]);
for(var j=0;j<a2.length;j++) //loop2
{
console.log(a2[j]);
}
}
Sample Output:
1st iteration of loop1:
1abcde
2nd iteration of loop1:
2abcde
and so on...
For every iteration of loop1,loop2 iterates 4 times(j<5).
Hoping I got your question right...This could be an answer.!

js Array undefined after json declaration

I m new a web developer and i face up the following problem:
"Cannot read property 'length' of undefined"
my code:
var data=();
for(var i;i<parseInt(window.localStorage["numOfInserts"]);i++){
data["category_name"]=localStorage.getItem(("category_name_"+i).toString());
data["category_id"]=localStorage.getItem(("category_id_"+i).toString());
data["provider_name"]=localStorage.getItem(("provider_name_"+i).toString());
data["provider_id"]=localStorage.getItem(("provider_id_"+i).toString());
data["appointment_date"]=localStorage.getItem(("appointment_date_"+i).toString());
data["appointment_time"]=localStorage.getItem(("appointment_time_"+i).toString());
}
$scope.allAppointments=dataArray;
for(var i=0;i<dataArray.length;i++){
$scope.showme[i]=false;
}
After some research I understand that the problem caused to the fact that data is an array but I try to turn it to json, but
var data ={};
gives me the same error as before.
Please Help me
I think this is what you're looking for, see code comments:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array, using the information
// from local storage. Note that you don't need toString() here.
// Once we've created the object (the {...} bit), we push it onto
// the array
data.push({
category_name: localStorage.getItem("category_name_"+i),
category_id: localStorage.getItem("category_id_"+i),
provider_name: localStorage.getItem("provider_name_"+i),
provider_id: localStorage.getItem("provider_id_"+i),
appointment_date: localStorage.getItem("appointment_date_"+i),
appointment_time: localStorage.getItem("appointment_time_"+i)
});
}
This does the same thing, it's just more verbose and so could help you understand more clearly what's going on:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array
var obj = {};
// Fill it in from local storage. Note that you don't need toString() here.
obj.category_name = localStorage.getItem("category_name_"+i);
obj.category_id = localStorage.getItem("category_id_"+i);
obj.provider_name = localStorage.getItem("provider_name_"+i);
obj.provider_id = localStorage.getItem("provider_id_"+i);
obj.appointment_date = localStorage.getItem("appointment_date_"+i);
obj.appointment_time = localStorage.getItem("appointment_time_"+i);
// Push the object onto the array
data.push(obj);
}
You need to create an array(dataArray before the loop), and create a new object in each iteration and set the property values for that object then add the object to the array like below
var dataArray = [],
data, numOfInserts = parseInt(window.localStorage["numOfInserts"]);
for (var i = 0; i < numOfInserts; i++) {
data = {};
data["category_name"] = localStorage.getItem(("category_name_" + i).toString());
data["category_id"] = localStorage.getItem(("category_id_" + i).toString());
data["provider_name"] = localStorage.getItem(("provider_name_" + i).toString());
data["provider_id"] = localStorage.getItem(("provider_id_" + i).toString());
data["appointment_date"] = localStorage.getItem(("appointment_date_" + i).toString());
data["appointment_time"] = localStorage.getItem(("appointment_time_" + i).toString());
dataArray.push(data)
}
$scope.allAppointments = dataArray;
for (var i = 0; i < dataArray.length; i++) {
$scope.showme[i] = false;
}
It looks like you're trying to create an associative array, so the first line should indeed be
var data = {};
The next part is fine, but then it looks like you want to enumerate the keys
for(var i=0;i<Object.keys(data).length;i++){
$scope.showme[i]=false;
}

Comparing one array value with another array

I have an array with values like :
userID: ["55f6c3639e3cdc00273b57a5",
"55f6c36e9e3cdc00273b57a6", "55f6c34e9e3cdc00273b57a3"];
$scope.userList : [Object, Object, Object, Object, Object],
where each object has an ID property of which i am comparing.
I want to compare whether the each userID array value exist in userList array or not.
$scope.userInfo = function(userID) {
var userDetails = [];
for (var i = 0; i < $scope.userList.length; i++) {
(function(i) {
for (var j = i; j < userID.length; j++) {
if ($scope.userList[i]._id === userID[j]) {
userDetails.push($scope.userList[i]);
}
}
})(i)
}
return userDetails;
};
The problem i am facing is for each userID in the array, i want to compare it with all the items in userList object to match.
The above code is not working. Its not comparing each array values with the entire object.
Instead of using 2 nested loops, convert $scope.userList into an object that has the userID as the key. Then you can loop through your userID array and quickly check if a user with the same key exists in your new object.
By removing the nested loops, the code below runs in linear time instead of n^2, which is beneficial if you have large arrays. And if you store $scope.userList as an object that's keyed by its userId, then you can save even more time by not having to create the index each time the function is run.
$scope.userInfo = function(userID) {
var userList = {};
//create object keyed by user_id
for(var i=0;i<$scope.userList.length;i++) {
userList[$scope.userList._id] = $scope.userList;
}
//now for each item in userID, see if an element exists
//with the same key in userList created above
var userDetails = [];
for(i=0;i<userID.length;i++) {
if(userID[i] in userList) {
userDetails.push(userList[userID[i]]);
}
}
return userDetails;
};
try this
$scope.userInfo = function(userID) {
var userDetails = [];
for (var i = 0; i < $scope.userList.length; i++) {
for (var j = 0; j < userID.length; j++) {
if ($scope.userList[i]._id === userID[j]) {
userDetails.push(userID[j]);
}
}
}
return userDetails;
};
Changes in this lines on if statement
var j = 0;
and
userDetails.push(userID[j]);
You should try using $filter.
JS:
var userIds = ["55f6c3639e3cdc00273b57a5",
"55f6c36e9e3cdc00273b57a6", "55f6c34e9e3cdc00273b57a3"];
$scope.userList = [
{id: "55f6c3639e3cdc00273b57a5", name: "ASD"},
{id: "55f6c36e9e3cdc00273b57a6", name: "XYZ"}
];
$scope.filteredList = $filter('filter')( $scope.userList, function(user){
return userIds.indexOf(user.id) != -1;
});
http://plnkr.co/edit/J6n45yuxw4OTdiQOsi2F?p=preview

Constructing json object using javascript

I am facing issues while constructing an object using javascript. I want this:
{
"p_id": "2",
"p_name": "weblogic",
"ip_list": [
{
"ip_id": 2690
},
{
"ip_id": 2692
},
{
"ip_id": 2693
}
]
}
Below is the javascript code that I am using to get the data into the object:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push("ip_id": selectedArray[index]);
}
I am able to construct the properties for p_id and p_name but struggling to create the the ip_list. Please let me know how to get this constructed using javascript.
Code for posting to the server:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = 2;
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
console.log (secTagJSON);
console.log (JSON.stringify(secTagJSON));
$http.post("http://server:port/api/v1/tags").
success(function(data) {
console.log (data)
});
Simply do this:
var obj = { ip_list: [] };
obj.p_name = "weblogic";
obj.p_id = "2";
for (var i = 0, j = selectedArray.length; i < j; i++)
obj.ip_list.push({ ip_id: selectedArray[i] });
Note that your ip_list is actually an array of objects. So, when you iterate over it, remember that each var item = json.ip_list[i] will return an object, that you can access its properties using: item['ip_id'].
Note that obj is an Javascript object, it is not an JSON. If you want the JSON, you can use JSON.stringify(obj). This will return your JSON (string).
Hope I've helped.
Try:
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
secTagJSON.ip_list = [];
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
you forgot your {} around "ip_id": etc...
You also need to declare that ip_list is an array.
Your ip_list is an array of objects. I would guess that your script was not running as it was.
Posting to your server you should use:
$http.post('server:port/api/v1/tags', secTagJSON).sucess(...

Categories

Resources