i'm trying to create object named client. and put it into a array. And after this, read the name of the 1st client.
Exemple :
client1 {nom : "marco", prenom : "chedel", adresseMail : "ssss#ggg.com"};
and put this client into an array like bellow.
listClients[client1]
what i did :
var listClients = [];
var client1 = {nom : "chedel",prenom:"Marco",adresseMail:"marco#gmail.com"};
listClients.push(client1);
var client2 = {nom : "De Almeida",prenom:"Jorge",adresseMail:"jorge#gmail.com"};
listClients.push(client2);
function afficheClients(tableau){
for (i=0;i<tableau.length;i++)
{
var c = tableau[i];
document.write(c[adresseMail]);
// This ^^ doesn't work, it says :adresseMail isn't definied in c
}
}
afficheClients(listClients);
You're treating adressMail as a variable and not as a string:
use
document.write(c["adresseMail"]);
There are two ways to access properties of an object:
obj.prop
obj['prop']
You are doing the following mixture which doesn't work: obj[prop].
Fix your code to c.adresseMail or c['adresseMail'] and it will work.
Either reference it using a string:
document.write(c['adresseMail']);
or using dot notation:
document.write(c.adresseMail);
And, yes - document.write should be avoided.
Related
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.
var a = "act";
db.s.findOne( {
BrandId: doc.BrandId,
a : {$exists:false}
} ).a;
I try to pass the value of variable "a" to my MongoScript. But it looks it can not be simply used. anyone can help?
Build your query step by step and do not use . use [] instead
var a = 'act';
var query = {BrandId: doc.BrandId};
query[a] = {$exists:false};
db.s.findOne(query)[a];
Note:
query.act == query['act'].
Just some javascript tricks.
I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];
Consider i am having an object "req".
When i use console.log(req) i get
Object { term="s"}
My requirement is to append an value with the existing object.
My expected requirement is to be like this:
Object { term="s", st_id = "512"}
Is it possible to do the above?
If yes, how ?
Thanks in advance..
There are several ways to do it;
Plain javascript:
var req = { "term" : "s" };
req.st_id = "512";
Because javascript objects behaves like associative arrays* you can also use this:
var req = { "term" : "s" };
req["st_id"] = "512";
jQuery way $.extend():
var req = { "term" : "s" };
$.extend(req, { "st_id" : "512" });
You can do this in a couple of ways:
req.st_id = "512";
or
req["st_id"] = "512";
The second of these is especially useful if the variable name is dynamic, e.g. a variable could be used instead of the string literal:
var key = "st_id";
req[key] = "512";
Yes this is possible, to add properties to a value simply use the following syntax:
req.st_id = "512";
In Javascript The Good Parts, it states:
So I would expect the following code example to output 1001 since "objects are never copied but passed around by reference", so why does it output 0000?
var page_item = {
id_code : 'welcome',
title : 'Welcome',
access_groups : {
developer : '0010',
administrator : '0100'
}
};
page_item.access_groups.member = '0000';
var member = page_item.access_groups.member;
member = '1001';
$('p#test').html(page_item.access_groups.member); //should be "1001" but is "0000"
Added:
#Gareth #David, thanks, this is what I was trying to show in this example, works:
var page_item = {
id_code : 'welcome',
title : 'Welcome',
access_groups : {
developer : '0010',
administrator : '0100'
}
};
var page_item2 = page_item;
page_item2.access_groups.developer = '1001';
$('p#test').html(page_item.access_groups.developer); //is '1001'
Don't think of pass-by-reference in the C++ context, because it's not the same.
var member = page_item.access_groups.member // Sets member to this value
member = '1001'; // Now sets it to another value
If there was a method on strings which changed them, then this:
member.removeLastLetter();
would alter page_item.access_groups.member. However, with your = you are changing the variable's reference, not the object it previously referenced
Because page_item.access_groups.member is a string and not an Object.
This is probably getting bashed by JS-Gurus but basically it goes down like this:
Objects are passed by reference.
Strings (numbers, etc... basically 1 dimensional variables) are passed by value.
I did try and understand the lengthy explanations on data types but I seriously needed some work done and haven't gotten time to look at it more closely.