Why is it returning undefined? - javascript

I want to store as the following method, and get the constant value, by querying using key to find value or by value to find the key
function my_reference() {
return {
30:'',
31:'ERR591',
32:'ERR761',
33:'ERR671',
34:'ERR551',
};
}
console.log( my_reference[31],
my_reference.31,
my_reference().31,
my_reference()[31]
);

my_reference[31],
Trying to read a property (which doesn't exist) of a function. The property is on the object that is the return value of calling the function.
my_reference.31,
Trying to use a number as an identifier. This isn't allowed.
my_reference().31,
Trying to use a number as an identifier. This isn't allowed.
my_reference()[31]
This works

You need to execute the function with my_reference() and after that access the property you want to.. but the keys in javascript objects are always strings:
console.log(my_reference()['31']);

You don't need to use a function to store the references:
var reference = {
30:'',
31:'ERR591',
32:'ERR761',
33:'ERR671',
34:''
};
console.log(reference[31]);

You have to call function if you want it to return result, function called by :
my_reference()
So the both first lines will not work because my_reference will return the function it self and not call it :
my_reference[31]
my_reference.31
The third also will not work console.log(my_reference().31); because attribute can't be numeric.
Hope this helps.

Here is the fixed code
function my_reference() {
return {
_30:'',
_31:'ERR591',
_32:'ERR761',
_33:'ERR671',
_34:'ERR551'
};
}
var f = my_reference();
console.log(f["_31"]);
console.log(f._31);
console.log(my_reference()._31);
console.log(my_reference()["_31"]);
Variables can't be named with just numbers
The first two should be the returned object

Related

Preventing higher order array methods from throwing an error

Is there a way to prevent errors from being thrown while filtering?
The below function sometimes fails at conversationMember.Name.toLowerCase() when there is no conversationMember.
If it helps, this is also a computed property in a Vue application.
Should you need more information, please just ask!
filteredConversations() {
var self = this;
var filteredConvos = self.conversations;
filteredConvos = filteredConvos.filter(conversation => {
return conversation.MembershipData.some(conversationMember => {
return conversationMember.Name.toLowerCase().includes(
self.conversationSearchTerm.toLowerCase()
);
});
});
return filteredConvos;
},
This doesn't seem to have anything to do with arrays.
From your code I understand conversationMember.Name is supposed to be a string (because you're calling .toLowerCase() on it), which means incudes here is not Array.prototype.includes, but String.prototype.includes, especially since self.conversationSearchTerm seems to also be a string (you're also calling .toLowerCase() on it).
So, the problem is you're using includes on something that should be a string but is not. The simple fix is to default it to an empty string when it's falsy:
return (conversationMember.Name || '').toLowerCase().includes(
(self.conversationSearchTerm || '').toLowerCase()
);
As a side note, you don't need the var self = this;. this is available inside your filter since the filter is an arrow function. So your function (I'm guessing it's a computed but it can as well be a method) could look like this:
filteredConversations() {
return this.conversations.filter(c =>
c.MembershipData.some(md =>
(md.Name || '').toLowerCase().includes(
(this.conversationSearchTerm || '').toLowerCase()
)
)
);
}
One last note: this will still fail if any of your conversations does not have a MembershipData holding an array. To get around that, you could default it to an empty array on the fly:
...
(c.MembershipData || []).some(md =>
...
As expected, any conversation without an array in MembershipData will be filtered out by the function (not included in the result) - because .some(condition) will return false when called on an empty array.

Difference between obj.key=value and obj.set(key, value)?

So while trying to update a document in mongoose, I realized that when I do obj.key=value to a document I obtained with Model.findOne(), it doesn'st assign the property to its value. But after trying obj.set(key, value), the property is assigned to its value in the document. So why is that? Usually when i do the first method to an object, the object gets the property. What is the .set() function? Does it have something to do with mongoose?
//this works
async function updateItem(){
let updatedItem = await Item.findOne({name:req.body.itemName});
Object.entries(req.body).forEach(elem=>{
if(elem[0]!=="itemName"){
updatedItem.set(elem[0], elem[1]);
};
});
};
updateItem();
});
//this doesn't work
async function updateItem(){
let updatedItem = await Item.findOne({name:req.body.itemName});
Object.entries(req.body).forEach(elem=>{
if(elem[0]!=="itemName"){
updatedItem.elem[0] = elem[1];
};
});
};
updateItem();
});
It means that updatedItem is not an object, it's a Map, and to add items to a Map you need to use the get method.
Another thing to point out is that when you set updatedItem.elem[0], you're literally trying to add the key "elem[0]" to updatedItem. To fix this, you need to use dynamic property notation with square brackets:
updatedItem[elem[0]] = elem[1];
This makes a new key with the value of elem[0], instead of the key being elem[0].

Return filtered array in javascript

I though this was going to be straightforward. I have a dataset containing (foreach country) name, imfcode, lat,lon. I want to pass a code to a function that will filter the dataset returning the info that correspond to the code passed to it. So if I pass 512 I should get information relating to Afganistan. here my function, would someone mind telling me what I'm doing wring
function loadTrade(imfCode) {
console.log ("Country code= ",imfCode)
var sourceCountry=dataset.filter function(el){
return el.imfcode===imfCode
}
console.log ("Source country= ",sourceCountry)
}
I keep getting an unexpected token and just can't see it. Many thanks
You missed the Parenthesis after dataset.filter
Change it to :
function loadTrade(imfCode) {
console.log ("Country code= ",imfCode)
var sourceCountry=dataset.filter(function(el){
return el.imfcode===imfCode;
});
console.log ("Source country= ",sourceCountry);
}

Why is my bulk replace function not working?

I have a function that uses the underscore.js each function to just call a string replace on each item in a list. (Actually a pair of lists):
//Base object
buckets = {
counters: ["stats.REPLACE.msg_delivered",
"stats.REPLACE.delivery_failed"],
timers: ["stats.timers.REPLACE.msg_delivery_timer.median",
"stats.timers.REPLACE.msg_delivery_timer.mean",
"stats.timers.REPLACE.msg_delivery_timer.std",
"stats.timers.REPLACE.msg_delivery_timer.upper"]
};
//function in question
_getNodeTargets = function(node) {
var targets = buckets;
_.each(targets.counters, function(bucket) { bucket = bucket.replace("REPLACE", node);});
_.each(targets.timers, function(bucket) { bucket = bucket.replace("REPLACE", node);});
return targets;
}
I can step into the each function and see that the strings are being replaced and assigned back to bucket. However, when I hit the return the targets object is unchanged with REPLACE still in each of the strings.
I have no doubt I am doing something dumb but for whatever reason I just can't see it.
Thanks in advance!
You have to make use of the other arguments _.each gives your callback:
_.each(targets.counters,
function(bucket, i, target) {
target[i] = bucket.replace("REPLACE", node);
});
The reason for this is that bucket itself is a reference to a string; replacing that reference with one of your own does not also replace the reference stored in the collection (that keeps pointing to the unmodified version). In contrast, target[i] does go and update the collection so the change is visible even after your callback returns.

Need to get the value of a variable which is sent as a string?

I'm sending a string as parameter to a function, but i already have a global variable in that name, i want to get the value of that variable but its sending as undefined..
My example code
i have a array as reg[0][0],reg[0][1],reg[1][0],reg[1][0],reg[2][0],reg[2][1]
and i have some global variables as tick1, tick2, tick3...
it will either have the values as 0,1 or 2
and in a function i called
calc_score(id) //id will return as either tick1,tick2,tick3
{
alert(eval("reg[id][1]")); // it should return the value of reg[0][1] if id is 0
}
But its not working.
The id wont be a numeral it will be string .. So how can i do this?
You shouldn't use eval for things like this. If you need to convert id to a number, use the unary + operator:
calc_score(id) //id will return as either tick1,tick2,tick3
{
alert(reg[+id][1]); // it should return the value of reg[0][1] if id is 0
}
or parseInt()
calc_score(id) //id will return as either tick1,tick2,tick3
{
alert(reg[parseInt(id, 10)][1]); // it should return the value of reg[0][1] if id is 0
}
If you need to parse a string like "tick1, tick2" then you have a few options. If the first part will always be "tick", you can slice the end off the string like so:
calc_score(id)
{
id = +id.slice(4); // or +id.substring(4) if you prefer
alert(reg[id][1]);
}
If tick1, tick2, tick3 are global variables, then instead of using eval(), you should reference them via the window object like so:
calc_score(id) //id will return as either "tick1","tick2","tick3"
{
alert(window[id]);
}
Use this:
alert(reg[Number(id)][1]);
of course you should check that id can be cast to a number before you do it. I don't really think you need the eval, unless you are trying to do something else that you haven't mentioned.
Oh! You change the code like the following:
calc_score(id) //id will return as either tick1,tick2,tick3
{
alert(eval("reg[" + id + "][1]")); // it should return the value of reg[0][1] if id is 0
}

Categories