Length of and iterating array that is using custom properties - javascript

var profileDataCalls = [];
profileDataCalls['Profile'] = GetUserAttributesWithDataByGroup;
profileDataCalls['Address'] = GetUserAddresses;
profileDataCalls['Phone'] = GetUserPhoneNumbers;
profileDataCalls['Certs'] = GetUserCertifications;
profileDataCalls['Licenses'] = GetUserLicenses;
profileDataCalls['Notes'] = GetUserNotes;
My problem is the above JavaScript array is only a length of 0. I need an array that can be iterated over and holds the key(string) and value?

You want:
var profileDataCalls = {
'Profile' : GetUserAttributesWithDataByGroup,
'Address' : GetUserAddresses,
'Phone' : GetUserPhoneNumbers,
'Certs' : GetUserCertifications,
'Licenses' :GetUserLicenses,
'Notes' : GetUserNotes
};
Then you can access the values with, for example, profileDataCalls.profile or profileDataCalls[profile] (to retrieve whatever value is represented by the variable GetUserAttributesWithDataByGroup)
To iterate through the object, use:
for (var property in profileDataCalls) {
if (profileDataCalls.hasOwnProperty(property)) {
console.log(property + ': ' + profileDataCalls[property));
}
}

Javascript doesnt have associative arrays per say , what you are doing is adding properties to the Array instance. IE doint something like
profileDataCalls.Notes = GetUserNotes;
so you cant really use length to know how many properties your array would have.
now if your issue is iterating over your object properties , you dont need an array , just use an object :
profileDataCalls = {}
then use a for in loop to iterate over the keys :
for(var i in profileDataCalls ){
// i is a key as a string
if(profileDataCalls.hasOwnProperty(i)){
//do something with profileDataCalls[i] value , or i the key
}
}
it you have different requirements then explain it.
now the tricky part is profileDataCalls[0]="something" would be valid for an object({}), you would create a property only available through the lookup (obj[0]) syntax since it is not a valid variable name for javascript.
other "crazy stuffs" :
o={}
o[0xFFF]="foo"
// gives something like Object {4095:"foo"} in the console

Actually it also works like this:
var profileDataCalls = [{
Profile: GetUserAttributesWithDataByGroup(),
Address: GetUserAddresses(),
Phone: GetUserPhoneNumbers(),
Certs: GetUserCertifications(),
Licenses: GetUserLicenses(),
Notes: GetUserNotes()
}];
Then you can access the values with, for example, profileDataCalls[0].profile or profileDataCalls[0]["profile"].
To iterate through the object, you can use:
for (key in profileDataCalls[0]) {
console.log(profileDataCalls[0][key]);
}
Since this is an associative array, I never understood why people are saying its not possible in Javascript...in JS, everything is possible.
Even more, you could expand this array easily like this:
var profileDataCalls = [{
Profile: GetUserAttributesWithDataByGroup(),
Address: GetUserAddresses(),
Phone: GetUserPhoneNumbers(),
Certs: GetUserCertifications(),
Licenses:GetUserLicenses(),
Notes: GetUserNotes()
}{
Profile: GetUserAttributesWithDataByGroup(),
Address: GetUserAddresses(),
Phone: GetUserPhoneNumbers(),
Certs: GetUserCertifications(),
Licenses: GetUserLicenses(),
Notes: GetUserNotes()
}];
And access the array entries with profileDataCalls[0]["profile"] or profileDataCalls[1]["profile"] respectively.

What you want is an object:
Try
var profileDataCalls = new Object();
then reference your data as you do already.

Related

How to assign specific objects of an array into another array of objects?

I have array of objects named tickets and I want to pick some specific objects from tickets like number,desc and state and assign them to new array of objects say myarr. I'm writing the below code but it says number is undefined. What am I doing wrong ?
$scope.myarr=[{
number:"",
desc:"",
state:""
}
];
for(var i=0;i<$scope.tickets.length;i++){
$scope.myarr[i].number=$scope.tickets[i].number;
$scope.myarr[i].desc=$scope.tickets[i].short_description;
$scope.myarr[i].state=$scope.tickets[i].state;
}
You need do something like this.
$scope.myarr=[];
for(var i=0;i<$scope.tickets.length;i++){
//Your Conditions
var object={
"number":$scope.tickets[i].number,
"desc" :$scope.tickets[i].short_description,
"state":$scope.tickets[i].state
}
$scope.myarr.push(object);
}
$scope.myarr = [];
angular.forEach($scope.tickets, function(ticket) {
this.push({number:ticket.number, state: ticket.state});
}, $scope.myarr);
If you don't need to support IE < 9, there is a handy function called map which is useful in this case
$scope.myarr = $scope.tickets.map(function(ticket) {
// return the element to be inserted in the new array
return {
number: ticket.number,
desc: ticket.short_description,
state: ticket.state
};
});

Accessing a associative array

Im trying to create a function that allows us to enter a persons name and their age. It will then be saved into an array.
var personnes=[];
function ajoutePersonne(n,a){
personnes["Nom"]=personnes.push(n);
personnes["Age"]=personnes.push(a);
personnes["Enfant"]="";
}
ajoutePersonne("Julie",100);
ajoutePersonne("Sarah",83);
ajoutePersonne("Jennifer",82);
ajoutePersonne("Olivia",79);
ajoutePersonne("Marge",55);
ajoutePersonne("Mathilde",48);
ajoutePersonne("Joanne",45);
ajoutePersonne("Isabelle",47);
ajoutePersonne("Celine",23);
ajoutePersonne("Caroline",29);
ajoutePersonne("Wendy",24);
ajoutePersonne("Kaliste",26);
ajoutePersonne("Karine",22);
ajoutePersonne("Sophie",28);
ajoutePersonne("Orianne",25);
ajoutePersonne("Alice",21);
print(personnes[1].Nom);
How come when im trying to access the 2 second person in the array under the category "Nom", Nothing shows up.
You need to put an entire object in the array, not push the name and age seperately:
var personnes=[];
function ajoutePersonne(n,a){
personnes.push({ "Nom" : n, "Age" : a, "Enfant" : ""});
}
personnes is an array, so in javascript it can only have integer indexes.
To do what I think you want to do:
function ajoutePersonne(n,a){
var person = {nom: n, age: a, enfant: ""};
personnes.push(person);
}
Where "person" is a javascript object using JSON.
Arrays are only meant to store numeric indices, you can create members like Nom but these will in no way react like a normal numeric index.*
Either use an object, or push objects into your array.
var personnes=[];
personnes.push({ "Nom" : "Julie", "Age" : 100 });
personnes[0].Nom // -> Julie
or
var personnes={};
personnes["Julie"] = 100;
// equal to:
personnes.Julie = 100;
or
var personnes={};
personnes["Julie"] = {"age":100 /*,"more attributes":"here"*/}
However, the last two notations assume that the names are unique!
*You can do the following:
var ar = [];
ar.attr = 5;
ar.attr; // -> 5
ar.length; // -> 0, since attr is not enumerable
// also all other regular array operation won't affect attr

Getting nested backbone model attributes using some expression

I am using Backbone model shown below
var myModel = Backbone.Model.extend({
defaults:{
name: 'user',
address: {
city: '',
state: '',
area: {
code: '',
street: ''
//More properties
}
}
});
So I can able to access nested street property using
model.get('address').area.street
Now I have a string like
properties = 'area.street'
How do I use it to access the nested street property?
Is there any way from where we can directly access nested properties ?
You can potentially flatten the nesting with Underscore's flatten method, which will put the object in a one-item array and put street at the top level of that object:
var flatAddress = _.flatten(model.get('address'))
That doesn't quite help if you're working off 'area.street'. Given a string representing layers of dot notation, the string likely needs to be broken up in a way that JS objects can digest. Consider something like
var array = properties.split('.');
var fromAddress = model.get('address');
for (var i = 0; i < array.length; i++ ) {
fromAddress = fromAddress[array[i]];
}
or if Array.reduce is available/preferable:
var property = properties.split('.').reduce(function(prev,curr) {
return prev[curr];
}, model.get('address'));
Either would be worth putting as a property on the model to facilitate reuse.
Have a look at this question - the answers show how to use a constructor on your backbone.model and then do this:
constructor(input: IListItem) {
super();
for (var key in input) {
if (key) {
//this.set(key, input[key]);
this[key] = input[key];
}
}
}
using the this[key] = input[key] method of creating Backbone Models will allow you to write code like this:
model.get('address').get('area').get('street')
if you use ES5 syntax ( as described in the answer ) - you can even write code like this:
model.Address.Area.Street
Also, you may find this blog post helpful.

Accessing an associative array using jQuery

I have an associative array here -
var dataset = {
"person" : [
{"userLabels": ["Name","Role"]},
{"tagNames": ["lName","role"]},
{"tableClass": "width530"},
{"colWidths": ["50%","50%"]}
]
}
I tried accessing the 'userLabels' object using jQuery using various methods but I failed. I think I am doing something wrong with basics. I want the userLabels object to be accessed using jQuery and the result should be an array, so I can perform the jQuery.inArray() operation.
Firstly, here's how you can access dataset using the method you have.
var dataset =
{
"person" : [
{"userLabels": ["Name","Role"]},
{"tagNames": ["lName","role"]},
{"tableClass": "width530"},
{"colWidths": ["50%","50%"]}
]
};
alert(dataset['person'][0]['userLabels']); //style 1
alert(dataset.person[0]['userLabels']); //style 2
alert(dataset.person[0].userLabels); //style 3
//Also you can use variables in place of specifying the names as well i.e.
var propName ='userLabels';
alert(dataset.person[0][propName]);
//What follows is how to search if a value is in the array 'userLabels'
$.inArray('Name', dataset.person[0].userLabels);
I'd like to ask why you're doing this in a such an 'interesting way'. Why don't you just make them all objects?
That's what I would do if I were you because if you think about it, a person IS an object and it should be noted that arrays are basically objects in Javascript with a 'length' property, though I won't elaborate on it here (feel free to do some research though). I'm guessing it's because you don't know how to iterate over object properties. Of course if it makes more sense to you, go for it.
Note one of the differences between an array and an object is that object properties need to be defined; you'll notice that I gave 'Name' and 'Role' values of 'undefined' below.
In any case, here is what I would do:
var dataset =
{
"person" : {
"userLabels": {"Name" : undefined,"Role": undefined},
"tagNames": {"lName" : undefined,"role" : undefined},
"tableClass": "width530",
"colWidths": ["50%","50%"]
}
};
for (var i in dataset) { //iterate over all the objects in dataset
console.log(dataset[i]); //I prefer to use console.log() to write but it's only in firefox
alert(dataset[i]); // works in IE.
}
//By using an object all you need to do is:
dataset.person.userLabels.hasOwnProperty('Role'); //returns true or false
Anyways, hope this helps.
var basic = dataset.person[0].userLabels;
// | | |
// | | --- first element = target object
// | --- person property
// ---- main-object
var userLabels = dataset.person[0].userLabels;
if ($.inArray(yourVal, userLabels) !== -1) {
doStuff();
}

Assigning objects to keys inside a JavaScript object

I want to create an object like this:
var servers =
{
'local1' :
{
name: 'local1',
ip: '10.10.10.1'
},
'local2' :
{
name: 'local2',
ip: '10.10.10.2'
}
}
This is what I'm doing
$.each( servers, function( key, server )
{
servers[server.name] = server;
});
Where servers is an array of objects like these:
{
name: 'local1',
ip: '10.10.10.1'
}
But the code above does not assign any keys to the object, so the keys default to 0,1,2....
One potential bug I notice is that you're modifying the object that you are iterating over (servers). It might be good to create a new empty object that you modify in the loop.
Also, it'd help if you posted some sample data so we can run your code for ourselves.
Finally, you could try inserting a debugger keyword in there and stepping through the code.
In Chrome if You run this:
a = [];
b = {n:"c",i:"1.2.3.4"};
a[b.n] = b;
alert (a["c"].i);
alert (a.c.i);
You will got the "1.2.3.4" string as expected. But if you change the example as:
a = {};
b = {n:"c",i:"1.2.3.4"};
a[b.n] = b;
alert (a.c.i);
You will get the same "1.2.3.4" again :). So the answer is: your code assigns the properties to the objects as you asked. The only difference is that in the first example you used the array as object, and in second the simple object.
AFAIK [] in javascript is used to index arrays, while to access object properties you have to use dot notation. So your code should be:
$.each( servers, function( key, server )
{
var name = server.name;
eval("servers." + name + " = server");
});
Please try it out since I don't test it.

Categories