mongdb/nodejs: using variables in $inc doesn't work - javascript

I have the following that i entered into the mongo terminal and it works great
db.cars.update({'_id':'FordXdfg'},{$inc :{'attribs.0.totl':1}})
which basically updates an array using dot notation, the 0 is the index of the array.
this does work. but transferring it to node my 0 comes from a variable.
so i tried
var carIndex = 3;
cars.update({'_id':'FordXdfg'},{$inc :{'attribs.' + carIndex + '.totl':1}}, function (err, callback) ................)
seems to be invalid javascript, if i replace my carIndex with 3 then it works i.e.
cars.update({'_id':'FordXdfg'},{$inc :{'attribs.3.totl':1}}, function (err, callback) ................)
Any ideas?
thanks

When using that style of object initialization in JavaScript, property names must be string literals. When using the object initialization syntax, property names can not be constructed at run time in code. For example, you can only use literals like:
{
"name": "Martin"
"location": "Earth"
"value": 1234
}
You cannot do this:
var propName = "name";
var obj = {
propName: "Martin";
};
While it syntactically appears to work, you'll end up with an object that looks like:
{
propName: "Martin"
}
Again, that's because only literal values are accepted when constructing an object using the shortened syntax. It will not interpret variable values.
There are two other options for setting properties of a JavaScript object, either through simple dot-notation:
obj.name = "Martin";
Or, you can use bracket notation:
obj["name"] = "Martin";
As objects in JavaScript act like associative arrays in that you can define new properties/keys at runtime each with a value, either syntax above works, and both result in the same underlying storage (and can be used interchangeably).
So, you'll need to construct the $inc syntax separately using the other technique for setting object property values in JavaScript:
var inc = {};
inc["attribs." + carIndx + ".totl"] = 1;
Then use that inside of your update:
{ $inc: inc }

Related

How to destructure the return value of a function?

I'm looking for a better syntax for writing the following code, and I would like to know if there is an option for assigning the return value of a function by using a destructuring assignment:
const object = {
property: 10,
getFunction() {
return "getFunction value";
}
}
const {property, getFunction} = object;
console.log("Property: ", property, " getFunction: ", getFunction);
Here, this code returns the following, which is totally normal:
"Property: 10, getFunction: [Function: getFunction]"
I'd like to know if there is a syntax option to write something like: (won't work)
const {property, getFunctionValue: getFunction()} = object;
And get the "getFunction value" from the assignment.
Unfortuntely, the syntax you're looking for doesn't exist (I've also wanted to do it many, many times). You can't call a function you're retrieving as part of a destructuring operation.¹ You're not allowed to use an arbitrary expression for the "from" part of a destructuring pattern. Destructuring always does property access, not function calls.
You'll have to do it separately, e.g.:
const { property } = object;
const getFunctionValue = object.getFunction();
or similar.
¹ unless it's the getter function for an accessor property

What is function with brackets mean?

Does anyone know what is test[name] mean?
function test(value){
copy(value||{},this);
}
test[name] = function(){
return "test"
}
This will be easiest to explain with an example:
var name = "foo";
test[name] = function(){
return "test"
};
This would add a property named "foo" to the object test, and the value of that property is a function. It doesn't matter in this case that the object test is actually a function, you can assign properties to functions just like any other object in JavaScript.
You could call this function using any of the following methods:
test[name]()
test["foo"]()
test.foo()
Note that test[name]() will not work if the name variable is assigned to something different, for example name = 'bar'.
Javascript has two sets of notation for accessing objects, dot notation (obj.property) and bracket notation (object[property]). More on that at MDN.
test[name] = function (){} assigns an anonymous function to the name property on the the test object (which itself is a function). In this case (as noted by the comments) the variable name is being used to access the property.
This may seem a little strange at first, but it's helpful to remember that in javascript, functions are objects.
All functions in Javascript are also objects. This adds a property to the test function object with a value which is an anonymous function.
For example:
function test(){
return "foo";
}
// test is a function, so it is also an object and
// it can have properties assigned to it
test.x = function(){
return "bar";
};
test(); // "foo"
test.x(); // "bar"
Of course just like with any object you can also use bracket notation:
var name = 'hello';
test[name] = function(){
return "HELLO!";
};
test.hello(); // "HELLO!"
In JavaScript, functions are objects. They have properties. test[name] sets a property (named whatever the name variable holds) to a function.
when you have a javascript object with defined properties you can access the property either with the dot notation obj.property or with the square brackets notation obj[property]
the property could also be a function so if you have an object:
var test = {
foo : function(arg){ console.log(arg) },
bar : 'hello'
};
you can call test.foo('bar') also by doing test['foo']('bar')
This is especially useful in iterations or when you dont know a priori what the name of the property is going to be. For example:
var fun = 'foo';
test[fun]('hello world');
Naturally it's up to you to do proper checks such as
if ('function'==typeof test['foo']){ test['foo']('bar'); }
Also note that you can do checks on the fly like so:
test[ fun || 'foo']('hello');
Taken from the Mozilla page
One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of object members
There are two ways to access object members: dot notation and bracket notation (a.k.a. subscript operator).
So
test[name] = function (
means: there are (if everything is ok) two objects: test and name (and we know that at least test is present, because you defined it one line before: function test(value))
take the test object (if there isn't a test object an error will happen). Then access the key/value pair with the key calculated from the name object and there put a function.
Now, how the key is calculated from the name object? The same page from before tells us:
Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.
Note that the description is a little wrong... test[null] == test["null"] and test[undefined] == test["undefined"], so perhaps the truth is that under the covers something like String(key).valueOf() is done (the String function will convert null to "null" and undefined to "undefined")
Some examples (where => means "is equivalent to, with this values")
var name = 'foo';
test[name] => test['foo']
var name = 123;
test[name] => test['123']
var name = 123.3;
test[name] => test['123.3']
var name = new Date();
test[name] => test['Wed Aug 14 2013 17:35:35 GMT+0200 (...)']
var name = null;
test[name] => test['null']
var name = undefined;
test[name] => test['undefined']
var name = [];
test[name] => test['']
var name = [1,2,3];
test[name] => test['1,2,3']
var name = {};
test[name] => test['object Object']
and so on...
The brackets are how you reference a property via a key into the hash that javascript objects are.

returning the index name from JSON in JS

Imagine we have this JSON:
{ "A" : {"A1": "1" } }
How can I extract the actual index A1 ?
So that I can use it in JS like:
var index = "A1";
edit — in case you mean, "How can I extract the value at index A1", then you'd just use the dot or bracket operators:
var value = object.A.A1;
or
var index = "A1";
var value = object.A[index];
Else see below.
You can iterate through the property names of an object with the for ... in loop:
for (var propertyName in object) {
// ...
}
The loop will also include properties from the prototype chain, so you can avoid that (if you want) with a function called hasOwnProperty:
for (var name in object) {
if (object.hasOwnProperty(name)) {
// really is a local property
}
}
Newer browsers support a way to get the property names as an array:
var names = Object.keys( yourObject );
That list will only include "own" properties; that is, those for which hasOwnProperty() would return true.
Finally, there are ways that properties can be defined such that they're not "enumerable". Usually when that's done, you would generally not want to see them in for ... in anyway.

object Key in javascript class/dictionary?

I have a Javascipt object which I use as dictionary
var obj={
xxx:'1'
yyy:'2'
}
However -
xxx and yyy should be a jQuery object.
something like :
var obj =
{
$('#div1'):'1' ,
$('#div2'):'2'
}
is it possible ?
also, How can I get the "value" for key $('#div2') ?
p.s.
I the $.data cant help me here since its also a key value
and i need in the key - object Type also.
Object keys can only be strings ( or Symbol), period. See Member Operators - Property Names # MDN.
Choose a reasonable string representation, and use that. In this case, I'd say the selector string looks like a decent choice:
{
'#div1': '1',
'#div2': '2'
}
also, How can I get the "value" for key $('#div2') ?
Use one of the member operators, either dot notation
var obj = { /* stuff */ };
var value = obj.propertyName;
console.log(value);
or bracket notation (more useful for property names not known until runtime):
var value = obj['propertyName'];
Use a WeakMap which works like a dictionary where the key can be anything. Note that you cannot list all the keys of the map
const aMap = new WeakMap;
const anObject = {};
aMap.set(Number, "It's the Number class")
aMap.set(anObject, "It's an object")
console.log(aMap.get(Number)) // It's the Number class
console.log(aMap.get(anObject)) // It's an object

Get values from object if the name of the object is stored as a variable?

I have a JSON object return with the following format:
"miscObject": {
"205": [
{
"h": "Foo",
"l": "Bar"
}
]
}
miscObject contains somewhere over 1500 entries, each named incrementally.
How can I get to the values of 'miscObject.205.h' and 'miscObject.205.l' if I have "205" stored in variable without having to loop through all of the objects inside miscObject?
It seems that you're talking about Javascript objects rather than a JSON string.
x[y] and x.y are mostly interchangeable when accessing properties of Javascript objects, with the distinction that y in the former may be an expression.
Take advantage of this to solve your problem, like so:
var num = '205';
console.log(miscObject[num].l);
// ^^^^^
// \
// instead of `.num`, which wouldn't be the same as
// `num` is not the literal name of the property
Use the member lookup syntax
var miscObject = $.parseJSON(theJsonString);
var name = '205';
miscObject[name].h;
Object values can be accessed 2 ways--using the 'dot' notation as you mentioned, or by using []'s:
The following should work:
var result = miscObject["205"].h;
var miscObject = JSON.parse(your-JSON-object);
var value = miscObject['205'].h
You can do this to get the object:
num = '205'
miscObject[num]

Categories