I'm trying to create an associative array in javascript where an array is filled with dynamic data located in attr fields of checkboxes - called "path" and "name". I want to make it so that every time a checkbox is checked, its attr "path" is an index - as there are five checkboxes that can be checked that can be associated with that certain path. I want the array to be something like this if possible where the "name" attr is associated with the path ["path1","name1","name2","name3","name4","name5","path2","name1ofpath2"]
I tried using objects, but when I check the checkboxes I only get an alert saying "[object Object]"..... any ideas? perhaps my wording is confusing?
var array = {};
$(".checkbox").bind('change',function() {
var path = $(this).attr("path");
var name = $(this).attr("name");
array[path] = name;
The problem is not with your code, but with alert, which when passed an object will invoke its .toString() method which typically reports [object Object]. Try using console.dir() instead.
As for your object itself, what you have when you use {} is an object whose properties are equivalent to the keys of the associate arrays available in other languages, i.e.
var obj = {
path1: name1,
path2: name2,
...
};
It's not really an "array" at all.
Related
The document in the target collection ("myCollection") has a field called "japanese2". This is an array (or an object) that contains an object that contains a property called "japanese2a". The value of this property is initially set to 0 (although it may change later). I want to change this value to 100 with a script in node.js (I am using the Express framework). The database is Mongodb, the free cloud version called Atlas.
If I do this without using variables, it works well:
db
.collection("myCollection")
.updateOne({username:username}, {"$set":{"japanese2.0.japanese2a":100}});
However, if I try this using variables for both the field name, "japanese2", and the name of the element/property in the array/object, "japanese2a", it fails. I have tried the below and other variations but I couldn't find a solution. I have researched stackoverflow for an answer but couldn't find a solution.
There is only one element/property in the array/object to start with.
var field = req.body.fieldName; //want to set this for the field name="japanese2"
var task = req.body.question; //want to set this for the name of the element="japanese2a"
var myField = [task];
field = myField;
var fieldPos = field[0];
.
.
.
db
.collection("myCollection")
.updateOne({username:username}, {"$set":{[fieldPos]:100}});
The above creates a new field called "japanese2a":100" but it does not appear in the array under the field called "japanese2", which is what I want.
I don't get any error messages when I do the above in the console (probably mostly due to the fact that I haven't put in error statements/functions to catch errors), but the output is not correct.
Another way of updating that I found from here:
https://www.codementor.io/#prasadsaya/working-with-arrays-in-mongodb-16s303gkd3
that involves using something like this:
db.posts.updateOne(
{ _id : ObjectId("5ec55af811ac5e2e2aafb2b9"), "comments.user": "Database Rebel" },
{ $set: { "comments.$.text": NEW_CONTENT } }
)
doesn't work for me, as I don't know if the initial value of the element in the array will always be a zero or some other constant. And there is only one element in the array initially. I can only use the username for the match part in the updating. I can't make an expression that is a perfect match for some element in the array.
The update solution from here: MongoDB update data in nested field
db.users.update ({_id: '123'}, { '$set': {"friends.0.emails.0.email" : '2222'} });
works, and that is what I used successfully to update in the first updating attempt above, but I don't know how to incorporate variables into the updating operation, specifically a variable for the field name ("japanese2") that holds the array or the object, and the name of the first and only element/property in the array/object ("japanese2a").
EDITED: I asked for a solution for an "array" originally, but either a field that acts an array (that holds elements that act as objects) or an object (that holds other objects as properties) works in my case, so I edited the question body and title. Also, the accepted solution works with the field as an entity that holds an array, or as an entity that contains an object inside it.
In either case, if there is already a field with the appropriate name, an object is created (if it didn't already exist) as an object of that object called "field" or the array called "field", and the object's property is set as according to the variables in the script.
If the field doesn't exist, it's created (as an object), and this object contains another object that contains the property ("task" as the name and "100" as the value for the name-value pair). So the newly created "field" object contains an object as its property. The property of this object is a name-value pair of "japanese2a" and "100".
If the script is run again, with a different "task" name (eg. "japanese2b"), another property is created, with the name of "japanese2b" and the value of "100". It is created within that same object that is "inside" the "field" object, so the object field.0 (the object within the "field" object) ends up looking like this: {japanese2a: 100, japanese2b: 100}. And the object called "field" looks like this: {{japanese2a: 100, japanese2b: 100}}.
I think something like
var field = req.body.fieldName // japanese2
var task = req.body.question; // japanese2a
var updateObj = { $set : {} };
updateObj.$set[field + '.0.' + task] = 100
db
.collection("myCollection")
.updateOne({username:username}, updateObj);
Might work
I have an intention to set a field value of an object like this
$scope[nameOfField]=value;
which works if nameOfField is just field name.
However, if I define in $scope object "subObject":
$scope.subObject={};
var nameOfField='subObject.someSubField';
$scope[nameOfField]=12345;
this does not work. Apparently I can not address directly sub-object fields like this. I however do need to use nameOfField approach with sub-object fields, and appreciate hints how to make it work. I can not predict if subObject will be featured in nameOfField - it can be both name field and subObject.someSubField.
EDIT: Difference with the question Accessing nested JavaScript objects with string key is that I not only need to access value of object but modify it.
Well your current code would result into
$scope['subObject.someSubField']=12345;
which would be a syntax error. Correct would be
$scope[nameOfField1][nameOfField2]=12345;
So you need a function to archieve this. Here an example (obviously this has to be extended to support more then just the 2 levels):
var scope = {};
function setValue(scopeString, val){
var match = /(\w+)\.(\w+)/.exec(scopeString);
if(!scope[match[1]]) //create if needed
scope[match[1]] = {};
scope[match[1]][match[2]] = val;
}
function getValue(scopeString){
var match = /(\w+)\.(\w+)/.exec(scopeString);
return scope[match[1]][match[2]];
}
setValue('lvl1.lvl2', 1);
console.log(getValue('lvl1.lvl2'));
I have an array called 'inputs' that I want to push some values to.
I am wondering if this is the correct way to do so:
inputs.push(name: $('#uploaderName').name(), value: $('#uploaderName').val());
#uploaderName is the ID of a form field with the value I want pushed.
FYI, the 'inputs' array is created like this:
var inputs = data.context.find(':input').not(':button');
I have also tried this with no luck:
inputs.push({name: $('#uploaderName').attr("name"), value: $('#uploaderName').val()});
To explain a bit more, at the end of this script it calls:
data.formData = inputs.serializeArray();
and then that data is passed off to a PHP script. I need to be able to add a few values to 'inputs' before inputs.serializeArray() is called.
For jQuery collections, you can include additional Elements with .add().
inputs = inputs.add('#uploaderName');
jQuery collections aren't actually Arrays. They're just array-like, meaning they have a length and numeric properties, but they won't have Array methods like .push().
You are storing the object, so use {...} to make the object first, and store it into inputs array, like
inputs.push({name: $('#uploaderName').name(), value: $('#uploaderName').val()});
//----------^----------------------------------------------------------------^
Or
var myObj = {name: $('#uploaderName').name(), value: $('#uploaderName').val()};
inputs.push(myObj);
I'm learning js, find this code:
var arr = [
{id: 111, now: '12.02.2014'}
];
What is this? I know that var arr = [ ... ] - array, but what is {} in array and how i can work with this data and display this ?
{} is the syntax for creating an object. It's called an object initializer, but it's frequently called an "object literal".
So what you're doing there is creating an object which has id and now properties, and putting that object into an array as its only entry.
...how i can work with this data and display this ?
To display the id, for instance:
console.log(arr[0].id);
What that does:
arr[0] - retrieve the first entry in the array. In our case, it's an object.
.id - Get the value of the id property from that object.
We could also write it like this:
var obj = arr[0];
console.log(obj.id);
Alternately, if we didn't know in advance what property we wanted but we were given a string containing the name of the property, we could use [] with the object as well:
var nameOfProperty = "id";
var obj = arr[0];
console.log(obj[nameOfProperty]);
JavaScript has both the dotted syntax (obj.id), and the bracketed syntax (obj["id"]) for accessing object properties, where with the latter you can use any string (including one from a variable).
Yes, that is an object inside an array. In truth, all values, from numbers to functions to arrays, are actually objects.
You can access this object in the same way as you would any item of an array. (arr[0])
You can then access properties of the object, for example arr[0].id.
For more about objects, take a look at Objects on MDN.
I have to push elements in an associative array from another array after some processing and I'm doing something this:
for(var i in this.aNames) {
var a = this.aNames[i];
// some processing on a
aList[i] = a;
aList.push(i);
}
But it's not giving me the proper array.
EDIT :
Here aNames is an associative array like this
'1232':'asdasdasd',
'6578':'dasdasdas'
...... and so on of about 100 elements.
I'm using for here as I want to do some changes in every element of the array.
Then I'm displaying the result array on the page but it's showing the key value together with the array data.
I.e. it should only display asdasdasd or asdasdasd but it's displaying keys too, like 1232 asdasdasd 6578 dasdasdas.
There are multiple things which may go wrong...
Primarily, make sure that this is pointing to the correct context and that this.aNames is actually returning a complex object (associative array).
Also, what's aList? Is it an array? If it is, push should append your array with the key of the current member (the member's name).
If you want to append the values of the members on your source object, you need to do something like this:
var obj = {name: 'dreas'},
arr = []; // arr is an array
arr.push(obj["name"]); // arr now contains a single element, 'dreas'
In your for..in construct, you are both adding elements to an alleged array (aList) with push but also creating new members on your array (with the subscript notation, aList[i] = "asd" since i in this case (for..in iteration) refers to the member's name).
So, what you need to do is decide if you want to add elements to an array or members to an object, not both.
If you just want to clone an array, use a for loop. If on the other hand you want to clone an object, it's not that trivial because members can also be complex objects containing their own members, and simply doing arr[i] = obj.member will only copy a pointer to arr[i] if member is a complext object, not a value type.
Just to make sure my terminology is understandable:
var anObject = {name: "dreas"},
anArray = [1,2,3];
anObject["name"] <= member (results in "dreas")
anArray[1] <= element (results in 2)