I have a map object containing a list of data about people. Every person's name is unique. The data fields of each person may not contain the same type of information (ie - Joey contains a date field, but Jill does not).
I am wondering if I can access a certain part of my map by using a variable name as part of the map path. Consider the following:
var data = {
'Joey': {
'id': '912',
'date': 'May 14 2012',
},
'Jill': {
'id': '231',
'login': 'JillM',
}
}
var name="Joey";
var joeyDate = data. + name + .date; //This does not work. Is there an alternative?
Use this syntax:
data[name]["date"]
This is an alternative to data.Joey, which should also work, but is static.
You can also use:
data[name].date
The difference is exactly what you're inquiring about - [] notation is better for dynamic retrieval and possibly invalid keys that wouldn't be allowed with Javascript if using dot notation. For example, if you had a key of "date-born", you can't use data[name].date-born, but you can use data[name]["date-born"].
An example of using this is:
for (name in data) {
console.log(data[name].date);
}
But of course, date must be a property (where it isn't for "Jill"), otherwise undefined will be returned.
An alternative way: mapName.get(keyName).propertyName
In your case: data.get(name).date
Related
Don't know how to go about adding new fields into a map in Firestore using a variable rather then a hardcoded field name.
I have a data structure in firestorm. The collection is called webQuiz and the document is called '12345. The data structure looks like:
roomName: Demo0
roomNumber: 46532
people:{11111:"David, 22222:"Peter}
Note that people is a map data object.
I would like to add another field to the people map. The code below works but instead of the data looking like
people:{11111:"David, 22222:"Peter, 44444:"Cathy"} it looks like
people:{11111:"David, 22222:"Peter, x:"Cathy"}
How can I use a variable which holds the field name in this situation? The x should be a variable but it is picked up literally as a property.
function testing(){
var x = "44444"
var y = "Cathy"
var cityRef = db.collection('webQuiz').doc('12345');
var setWithMerge = cityRef.set({
people: {x: y}
}, { merge: true });
I expect the output in firestorm to be
people:{11111:"David, 22222:"Peter, 44444:"Cathy"} but the actual output at the moment is
people:{11111:"David, 22222:"Peter, x:"Cathy"}
Thanks
You'll need to use the full field path as the key of the update:
var setWithMerge = cityRef.set({
`people.${x}`: y
});
This will prevent re-writing the entire "people" field, since you are specifying which property of the map to change directly.
Note that the field name and the property name are separated by a period.
From pg-promise's example, one can format a query like below, where ${this~} becomes all of the keys in the object that is the second parameter of "format()".
// automatically list object properties as sql names:
format('INSERT INTO table(${this~}) VALUES(${one}, ${two})', {
one: 1,
two: 2
});
//=> INSERT INTO table("one","two") VALUES(1, 2)
Is it possible to also get all of the values of the object, without explicitly typing all of them? I want to do it like below (should do the same thing as the snippet above, but without typing all of the values):
format('INSERT INTO table(${this~}) VALUES(${this#})', {
one: 1,
two: 2
});
Is it possible to also get all of the values of the object, without explicitly typing all of them?
No, it is not possible, because while column names require the same-type SQL Name escaping, values do not, they require templating that's possible only via explicitly defined variables.
I want to do it like below...
For that you should use the helpers methods of the library:
const cs = new pgp.helpers.ColumnSet(['one', 'two'], {table: 'my-table'});
const query = pgp.helpers.insert(values, cs);
I lack some basics in these languages so it might be an easy question.
I receive an json encoded array of object from an ajax call. At the begining of it, I add some elements I need :
array_unshift($data, array('nbr' => 6,'Col1' => 'Company name',
'Col2' => 'Email','Col3' => 'Adress','Col4' => 'City',
'Col5' => 'Code','Col6' => 'Country));
In the success:function(msg) of the ajax I want to iterate through these elements to make them the headers of a table :
var qtt=msg[0].nbr;
$foo='<table>';
for (var i = 1; i<qtt; i++) {
$foo=$foo+'<th>'+msg[i].Col+i+'</th>';
}
$foo=$foo+'</table>;
I want to access the i'th element of msg and I know it is named 'Col'+i. To me, it looks simple and difficult at the same time.
I just don't know how to do this, no idea. Any help is welcome.
Edit :
With firebug I could retreive the answer of the ajax call. If it can help you here it is (the element are in french but it is exactly what I was talking about previously) :
[{"nbr":6,"Col1":"Nom soci\u00e9t\u00e9","Col2":"Email","Col3":"Adresse",
"Col4":"Ville","Col5":"Code postal","Col6":"Pays"},
{"Soc_Nom":"foo1","Soc_Email":"bar1","Soc_Adresse":"foobar1", "Vil_Nom":
"Foofoo1","Vil_Code_Postal":"1000","Pys_Nom":"Belgique"},{"Soc_Nom":
"Foo2","Soc_Email":"Bar2","Soc_Adresse":"foobar2","Vil_Nom":"Foofoo2",
"Vil_Code_Postal":"2000","Pys_Nom":"Belgique"}]
Ansewer :
No need to iterate through msg[] since all the info I wanted to access was in msg[0].
Using msg[0]['Col'+i] works perfectly.
If you're trying to access a property name dynamically, you can use an indexer with the property name as a string:
$foo=$foo+'<th>'+msg[i].Col+i+'</th>';
becomes
$foo=$foo+'<th>'+msg[i]['Col' + i]+'</th>';
msg[i].Col + i (your original code) is looking for a property named Col and trying to add the value of Col to the value of i.
The second example is building a dynamic property name 'Col' + i, and using brackets to access a property of that name on the msg[i] object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
I have an array called values. At present, I'm appending new data to this array as such:
values.push(guests);
The result of my array is something like this:
["123456789", "Joe", "Bloggs", "Test Corp", "fiji", true, "guest, guest 2, guest 3", true]
I have now realised that in its present state this data is useless to me as I cannot tell what each element is. In my example above, the first long number is an account number and the second element is a first name but these are liable to change. E.g the company name Test Corp may not always exist in the data. This means I cannot use the numerical key [3] to target it because it may not be present.
Therefore I need to code this data into something that I can assign both a label for the data, and the data value. I'm guessing the best way to do this would be with an JSON object.
How can I create a key->value pair object? I would need to replace my .push() code above to instead add the value of COMPANY NAME -> Test Corp so that it can be deciphered later.
For reference, I am then stringifying this data and using an AJAX request to POST it to a PHP script where it will need to be arranged into variables e.g $company_name = 'Test Corp';
You're talking about a plain JavaScript object. JSON is a transfer format inspired by JavaScript syntax.
To make an object, just initialize a variable:
var values = {};
And add properties:
values.accountNumber = "123456789";
values.firstName = "Joe";
etc. If you know the properties up front and have values available, you can make the object in one step:
var values = {
accountNumber: "12345678",
firstName: "Joe",
// ...
};
trying to invoke a backend php script which reads and writes to a mysql database and would like to define which field (aka column) I want to read or write from/to dynamically.
everything gets thru except the dynamic parameter name which I pass in as field to the javascript function.
if I hardcode field to 'mapstring' (which matches the column name in the mysql database), then it works. But writeabdata.php is written to write to any field name depending on what is passed into it.
What do I have to do to the field string parameter passed into writeabdata() so that it is passed correctly in the data portion of the .ajax call?
function writeabdata(table, id, field, mapstring) {
//alert ("table = "+table+" id = "+id+" field = \'"+field+"\' value = "+value);
$.ajax({
type: 'GET',
url: 'writeabdata.php',
data: {
'table': table,
'id': id,
field: mapstring
},
success: function (data) {
alert ("data Saved "+ data);
}
});
}
Generally when writing you'll want to use the "POST" type rather than the "GET" type. POST is for POSTING data to the data store, and GET is for RETRIEVING it. Without some more code, though, its hard to debug this, so I'm going to take a couple of shots in the dark.
First off, clean up the code a bit and unify your format - put "field" in quotes like your other items. While this may not solve your problem, the JSON standard is actually defined as using DOUBLE QUOTES only.
Second off, if we could see the PHP code, that would help - my guess is that there's something wrong with how the response is interpreted. I suggest that for debug purposes you get Fiddler running and inspect the actual request to make sure that you're sending all required fields to the server.
Once you update us with more info, I can update my answer - but I'd start by switching to POST.
Update
I think I misunderstood the question -- if you're looking to get data.field to really be data.somefield as in the name of that property could change to whatever you want, that's quite simple:
data[field] = mapstring
In other words:
function writeabdata(table, id, field, mapstring) {
//alert ("table = "+table+" id = "+id+" field = \'"+field+"\' value = "+value);
var dataObj = {
'table': table,
'id': id
};
dataObj[field] = mapstring;
$.ajax({
type: 'GET',
url: 'writeabdata.php',
data: dataObj,
success: function (data) {
alert ("data Saved "+ data);
}
});
}
Contrary to some of the comments you got, you can, as you see above, dynamically set property names using the array accessor on an object. And it works swimmingly. Build out your statically named data object properties, and then add the other ones via the array accessor.
You cannot set the field of an object literal (when you use {} directly in your code) using a variable.
For example:
var field = "b";
var myObject = {
"a": "A",
field: "B",
};
That object will look like this:
{
a: "A",
field: "B",
}
The reason this does not work is because fields are always considered to be strings. The fact that you do not need to put quotes around the field names is just language sugar, there to make it look better.
In order to create an object with a custom field you have to use the [] brackets, like this:
var field = "b";
var myObject = {
"a": "A",
};
myObject[field] = "B";
Which will then work as intended:
{
a: "A",
b: "B",
}
Here in your function you are taking 4 arguments- table, id, field, mapstring.. and then making the field:mapstring..
i.e you want the field value to be equal to mapstring than submit.. Why you want to take two arguments in a function to assign one's value to another... May be you just want field as 1 of the field of table.. So take 3 arguments- table, id, field..and assign the value of field similarly you assigned the values of table and id and see if it works...
Also replace GET with POST