Accessing a associative array - javascript

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

Related

AngularJS How to group/organize items in object in order to show them in the view

I have a URL with some parameters like this one:
http://localhost:9000/#/checkout/?title1=Sodadrink&quantity1=2&price1=129.95&title2=PolaryteGlasses&quantity2=1&price2=59.95#%2F
and I'm getting them with $location.search(), which returns them just fine in an Object like:
Object
price1: "129.95"
price2: "59.95"
quantity1: "2"
quantity2: "1"
title1: "Sodastream"
title2: "Polaryte – Óculos de Sol"
__proto__: Object
This is cool, but now I need to group each item like:
[item]
title : Sodastream
price : 129.95
quantity : 1
[item]
title : ---
price : ---
quantity : ---
I'm stuck in this part, I've though of counting the total items inside the object, 6, and them group them in groups of 3 by creating a new Object, but didn't work out.
Can you help me? Thanks.
Since the number of items in the URL may vary, it is best to not hardcode any number. For this, I am also assuming that every item has 3 properties - title, price and quantity.
Try this:
var numOfItems = Object.keys(input).length/3; // for example, 6 properties will mean 2 items
var output = [];
for (var i = 1; i <= numOfItems; i++) {
if (input["title"+i]) {
output.push({title: input["title"+i], price: input["price"+i],quantity: input["quantity"+i]})
}
}
The output array should contain the objects in the exact way you specified.
You will have to write a bit of javascript to do that.
Assuming that your object from above is called inputs
const MAX_ITEMS=9;
var outputs = [];
for (var i=1,i<MAX_ITEMS;i++) {
if (inputs["item"+i]) {
outputs.push({item: inputs["item"+i], price: inputs["price"+i],quantity: inputs["quantity"+i]})
}
}
Your data will be in the outputs variable

How would I go about using a multidimensional array variable in javascript

Hi there before I start I did try looking through the search about writing variables so if this has been asked and answered then I do apologise but this is baffling me ....
So here goes ..
example of what I am talking about
var i = e[ab]
var n = e[cd][ef]
var t = e[cd][gh]
I know that when I want var i I can put e.ab but how would I go about writing var n and var t
So assuming your object looks like this (based on your description, it sounds like you want to access an object which is the property of another object), and you want to access them through the indexer properties (which would be a property of a property).
var e = {
ab : "variableOne",
cd : {ef:"ef object"},
gh : {ij:"ij object"},
}
var i = e["ab"]
//if these are properties, then you need to add quotes around them
//to access a property through the indexer, you need a string.
var n = e["cd"]["ef"]
var t = e["gh"]["ij"]
console.log(i);
console.log(n);
console.log(t);
console.log("this does the same thing:")
console.log(e.ab);
console.log(e.cd.ef);
console.log(e.gh.if);
In your example the object would look like
//e is the parameter, but I show it as a variable to show
// it's relation to the object in this example.
e = {
now_playing: {artist:"Bob Seger"; track:"Turn the Page"}}
}
this is different than an array of arrays:
var arr = [
['foo','charlie'],
['yip', 'steve'],
['what', 'bob', 'jane'],
];
console.log(arr[0][0]); //foo
console.log(arr[0][1]); //charlie
console.log(arr[1][0]); //yip
console.log(arr[1][1]); //steve
console.log(arr[2][2]); //jane
https://jsfiddle.net/joo9wfxt/2/
EDIT:
Based on the JSON provided, it looks like parameter e in the function is assigned the value of the item in the array. With your code:
this line will display: "Rock you like a hurricane - Nontas Tzivenis"
$(".song_title .current_show span").html(e.title);
and this line will display: "Rascal Flatts - Life is a Highway".
$(".song_title .current_song span").html(e.np);
If it's not displaying you might want to double check your JQuery selectors. This ".song_title .current_song span" is selecting it by the classes on the element.
I think you are in need of a bit of a refresher on basic JavaScript syntax. Here's how you can assign an "empty object" to a variable, then start to assign values to it's properties:
e = {}
e.ab = {}
e.cd = {}
e.cd.ef = "data"
or you can use the associative array syntax for property access:
e = {}
e["ab"] = {}
e["cd"] = {}
e["cd"]["ef"] = "data"
You see the latter is using the object e like a two-deep associative array. Is that what you are looking to do?
JavaScript is not strongly typed. So an Array "a" could contain objects of different types inside.
var a = [ "a value", [1, 2, 3], function(){ return 5 + 2;}];
var result = a[0]; //get the first item in my array: "a value"
var resultOfIndexedProperty = a[1][0]; //Get the first item of the second item: 1
var resultOfFunc = a[2](); //store the result of the function that is the third item of my array: 7
Hope this helps a little.

Javascript arrays

Let's suppose I have an associative array like this one
var client1={
"id":"1"
"category":"Interiorism",
"photo1":"img/ClientCorp/photoClient1.jpg",
"photo2":"img/ClientCorp/photoClient2.jpg",
"photo3":"img/ClientCorp/photoClient3.jpg",
"photo4":"img/ClientCorp/photoClient4.jpg",
};
var client2={
.
.
.
};
allClients=[client1, client2..., clientx];
I want to set up a function that pushs the photo keys in an empty array. The problem is that not all the clients have the same number of photos, so I am using 'for'. Here is the function I wrote
function photoKeys()
{
var keyList=Object.keys(allClients[id]);
var numKey=parseInt(listaKeys.length);
var photoAlbum=[]; //here I want to put the photo URL's
for (i=2; i<=numFotos; i++)
{
????????????
}
}
Here is the problem, how I can write the photo object from the client array whith the i var from the 'for' function?
I tried this but didn't work
for (i=2; i<=numFotos; i++)
{
photoAlbum.push(allClients[id].photo+'i');
}
Your current code would be parsed like this:
photoAlbum.push(allClients[id].photo + 'i');
It would try to evaluate allClients[id].photo and then append the string i. You need to access the property name using bracket notation instead of dot notation.
You also have the symbol and string part backward, photo is the string and i is your index variable.
photoAlbum.push(allClients[id]['photo' + i]);
The big thing to understand is that client in your example isn't an array, it's an object.
var client1={
"id":"1"
"category":"Interiorism",
"photo1":"img/ClientCorp/photoClient1.jpg",
"photo2":"img/ClientCorp/photoClient2.jpg",
"photo3":"img/ClientCorp/photoClient3.jpg",
"photo4":"img/ClientCorp/photoClient4.jpg",
};
You can acquire an object's keys as an array using Object.keys(client1), or you can loop through all an object's keys using for...in syntax.
If you want to feed an arbitrary number (numFotos) of property values from your object into an array called photoAlbum, you can use the following syntax:
var i = 0;
for(var key in client1){
photoAlbum.push(client1[key]);
if(++i >= numFotos){
break; // break out of the loop if i equals or exceeds numFotos
}
}
First of all you should be accessing the photo paths like:
photoAlbum.push(allClients[id]['photo' + i]);
But i would really recommend you to change the format of your client object to something like this:
var client1 = {
"id" :"1"
"category" :"Interiorism",
"photos" : [
"img/ClientCorp/photoClient1.jpg",
"img/ClientCorp/photoClient2.jpg",
...
]
};
Or this, if you need to store those "photo1", "photo2" ids:
var client2 = {
"id" :"1"
"category" :"Interiorism",
"photos" : [
{
"id" : "photo1",
"path" :"img/ClientCorp/photoClient1.jpg"
},
...
]
};
Then you can iterate them way easier like this:
for(var i = 0; i < allClients[id].photos.length; i++){
photoAlbum.push(allClients[id].photos[i]);
//or this for the second format:
//photoAlbum.push(allClients[id].photos[i].path);
}

Length of and iterating array that is using custom properties

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.

Using concatenation and a passed parameter to loop through an array

var Animals = {
"Europe": { "weasel.jpg": "squeak", "cow.jpg": "moo"},
"Africa": { "lion.jpg": "roar", "gazelle.jpg": "bark"},
};
function region(a){
var b = "Animals."+a;
for(var index in b) {
var target = document.getElementById('div1');
var newnode = document.createElement('img');
newnode.src = index;
target.appendChild(newnode)
}
}
RELEVANT HTML
<li onclick="europe('Europe')">Europe</li>
Goal: on the click of the Europe <li>, pass the word Europe into my region function where it is then concatenated to produce Animals.Europe
This is in order to identify an array within the object structure at the top using the for(var index in Animals.Europe) loop. Why is the concatenation which produces Animals.Europe not treated in the same way as if I had typed this out?
In addition, you can see that I have used arrays to store an image source and description for different animals. Using my limited coding knowledge this was all I could think of. Is there an easier way to store image/description data in order to produce in HTML?
"Animals." + a is just a string value, e.g. "Animals.Europe", which is not the same thing as Animals.Europe. If you change the first line to var b = Animals[a];, you should be all set.
Edit: and as elclanrs pointed out, it should be region('Europe'), not europe('Europe').
Why is the concatenation which produces Animals.Europe not treated in the same way as if i had typed this out?
In this case the variable b is just a string ("Animals.Europe"), which is treated like any other string (i.e. a list of characters). This means that when you attempt to loop through it (for(index in b)) you will be looping over a simple list of characters.
What you can do instead is use the square brace notation of accessing an objects properties. This means you can instead write var b = Animals[a], retrieving attribute a from Animals. You can read more about working with objects in this way on this MDN page
You can access the europe property using the following
Animals[a]
Also you're calling a "europe" function when you should be calling "region"
You're not storing animals in arrays here, but in objects with the image names as keys. Usually you'll want to use relevant names as keys. For example if you want arrays of animals for each continent
var Animals = {
"Europe": [{
imageSrc: "weasel.jpg",
cry: "squeak"
},{
imageSrc: "cow.jpg",
cry: "moo"
}],
"Africa": [{
imageSrc: "lion.jpg",
cry: "roar"
},{
imageSrc: "gazelle.jpg",
cry: "bark"
}]
};
Now Animals['Europe'] gives an array of objects, where you could eventually store other properties. So if b is an array your loop will now look like:
var b = Animals['Europe'];
for(var i=0; i < b.length; i++) {
var target = document.getElementById('div1');
var newnode = document.createElement('img');
var animalData = b[i]; // The array item is now an object
newnode.src = animalData.imageSrc;
target.appendChild(newnode)
}

Categories