Access Object by variable - javascript

So basically I need to get a value out of a variable and insert it into a sequence.
I generally have no clue how to put this into words since I'm dutch but I hope you understand my question
var channelname = msg.channel.name;
"description": `${config.ticketlist.channelname.ticketmessage}`,
(Ofcourse highlights from the code)
But when I want to get the ticketmessage it doesn't work since channelname is not actually defined in my json file. It should be like ticket-001. But now its gonna search for channelname but not for the actual ticket name.

You can only use computed paths with bracket syntax. Use
"description": `${config.ticketlist[channelname].ticketmessage}`,
instead.

Related

TypeError: Cannot call method "indexOf" of null

I'm triying to find the records that includes "SO -" or "NS - SO" or "SO –" or "SWAT" on THE "RESUMEN" field from a CSV file to asigne a new category (in this cases would be "Call Center"). So, I used "indexOf" funtion witch worked so well.
The problem comes when I change the data source (It is a CSV too), this gave me next error on that step:
"Caused by: org.mozilla.javascript.EcmaError: TypeError: Cannot call method "indexOf" of null (script#2)"
The objective is to assign a category by identifying the words on the source file
My code
if (RESUMEN.indexOf("SO -")!=-1 || RESUMEN.indexOf("NS - SO")!=-1 || RESUMEN.indexOf("SO –" )!=-1 || RESUMEN.indexOf("SWAT")!=-1)
{
var RESULTADO = "Call Center"
}
else RESULTADO = ""
I expect to assigne call center category like I got with the first file (I did not change nothing)
regards!
You're overcomplicating the issue.
Before the answer, remember something, there are several steps, and combinations of steps, that achieve an incredible number of transformations to make usable patterns, the last resort IS User defined Java Expression.
Seems like what you want to achieve is a Value Mapping, thou the difference from a direct value map in your case, is that the row you're testing must contain "SO -", and the other cases, somewhere in the text.
With this simple filter, you can transform your data that contains those informations as you desire, and on the "FALSE" side, treat it for errors.
This will expand your transformation a bit, but when you need to change something it will be easier than with a single step with a lot of code.
As another answer pointed out, you can achieve the same result with different steps, you don't need the javascript step.
But, if you want to go that route, you should first convert null values into, e.g., empty strings.
Simply add this to the beginning of your javascript code:
if (!RESUMEN){ RESUMEN = ''}
That'll convert nulls to empty strings and then indexOf returns correctly.

JSON data and getting/changing a property in it using a variable

To begin, I am not sure if this question will make much sense. I will do my best to explain.
I am working on a project looking at U.S. Census bureau information. The part of the object that I am looking at looks like this: (Please note that this is only part of the object.)
Object {MTFCC: "G5020", OID: 207903717468543, GEOID: "13135050431", STATE:
"13", COUNTY: "135"…}
AREALAND: 5416158
AREAWATER: 34463
B19013_001E: "45543"
The part that I am interested in is: B19013_001E which happens to be the code for Median Household Income. In order to get specifically the Median household income I would do:
response.features[1].properties.B19013_001E
Everything works find up to this point. However, my problem is the following: I want to change that code to have other values. So, if the individual wants to look for median_male_age, whose code is B01002_002E I do not want to hard code in B01002_002E as the following:
response.features[1].properties.B01002_002E
The above line would work. But again I want something that can be determined by a variable so that I will not have to hard code in the special code. So, I want a code that is like this: (just an example!)
var value = prompt("What do you want to look at: ")
//In this case value would be the special code like B01002_002E which the user enters.
console.log(response.features[1].properties.value)
Whenever I do this, I get no information back. At first I thought I had the wrong type but I do not believe that is the issue. (I tried converting to a number and back to a string etc.) Any help on this will be great!
Expanding on my comment.
First, MDN has a great doc on Working with objects. It is worth the read.
Second, for your own edification, JSON is a string and not an object hence it's abbreviation of JavaScript Object Notation. What you have is colloquially referred to as a POJO or Plain Old Javascript Object. They are different. :)
Third, for your question in particular, you want to use bracket notation when accessing an object property via a variable. So in this case it would be:
console.log(response.features[1].properties[value])
Hope this helps!

Case Sensitive GET

I have an MVC application where I am passing some arguments via GET. Everything works great but some of the information I am passing I would like to keep the case of. For example one field I pass is title, so ?title=My Title that works great, except when I get to my controller method the value in the title field of my model is my title is there any way I can keep the case calling a controller in this manner?
This is how I am calling the controller in javascript like so:
var url = "#(Url.Content("~/Controller/Name/?title=My Title"))";
window.open(url, "_blank");
First make this function...
function firstCharsToUpperCase( char ){
return char[0].toUpperCase();
}
Then in your controller you should have access to params or a key/value pair of some sort like this...
params['title'] = params['title'].replace(/\b[a-z]/ig, firstCharsToUpperCase);
You would then reassign the key title to the new value of "My Title"
Also, params should be case insensitive. Perhaps there is something converting the URI?
Maybe its in the Url.content() function. Can we see what it does?
Also, here is an article regarding case sensitive routes Never Use Capital Letters
UPDATE
I found this
If the specified content path does not start with the tilde (~) character, this method returns contentPath unchanged.
here link
Perhaps what it is saying is that if the '~' is left off, you will get what you give it. Try it out and see?
Case sensitive URLs are not a good idea even when not causing SEO issue, its just a bad idea. I developed a solution where I passed an ID in the URL and queried the necessary data from the DB within my controller.

xml2js, attribute name contains a hyphen

Using xml2js to parse an XML file, I need to retrieve the value of an attribute which contains a hyphen in its name
<item cdr-id="1234">
<name>some text</name>
</item>
At the point where I'm trying to retrieve cdr-id, I already have a variable item which points to the item element. I've verified it's pointing to the proper node with
console.log(item.name);
and that returns the expected value some text. But when I try
console.log(item.$.cdr-id);
I get the completely reasonable error ReferenceError: id is not defined (I'd have been more surprised if id wasn't treated as a separate token).
Likewise,
console.log(item.$."cdr-id");
gets the message SyntaxError: Unexpected string.
Throwing JSON.stringify around it
console.log( JSON.stringify(item.$));
reveals the original attribute name: {"cdr-id":"CDR0000040222"}
Not having hyphens in the name in the first place just kicks the problem down the road a bit. Failing that, it looks like providing a custom attribute name processor is the way to go, but that smacks of being "too clever" with potential for confusion if anyone ever has to update this code.
Is there a better way to do this?
do like
console.log(item.$["cdr-id"]);

How to get values from an object without the object name in Javascript

The question sounds weird I know. But its a weird question. Let me clarify.
Im using the facebook graph api. The feeds for my page are returned in JSON and i have this bit of JSON here:
"message": "A3Media Uk Website is fully up and running! Tell your friends, We can't make Beautiful Websites without clients!\n - Alex Morley-Finch",
"message_tags": {
"116": [
{
"id": "514033508",
"name": "Alex Morley-Finch",
"offset": 116,
"length": 17
}
]
}
So from my knowledge, there is an object called message_tags which contains and array of objects called 116, and index 0 of this array contains and object with the variables id, name, offset and length.
Now what i want to do is, obviously replace the text "Alex Morley-Finch" within the message variable with the tag "name": "Alex Morley-Finch". Then using the id, length and offset i can replace the text with a html link to that profile using the ID!
This all seem pretty simple, however, i obviously want my code to be dynamic so the code will work for ANY tag at ANY position.
The name of the object array "116" always matches the offset contained inside it.
The actual question:
How can I dynamically get the name of the object Array (in this case '116')?
Because my code would be something like (pseudo code):
if message has tag
get name of tag
if message contains name of tag
replace message name using offset and length with html link tag with href = facebook url / id
end if
end if
This would leave me with my html representation of the "message"
The thing is i cant get the name of the message_tag because id have to do somthing like:
// data[index] represents the current message
var json = JSON.parse(XmlHttpResponse.responseText);
json.data[index].message_tags.116[0].name;
as we can see this is not dynamic. This code will ONLY work for this tag.
So how do i get the name without referencing 116? is it even possible?
i was thinking about trying iterating through 1, 2, 3, 4, 5 --> 116 but that would be very performance costly AND bad coding AND im not even sure if you can reference arrays through variable names... ... ...
Im really stumped.
Please Help!
Alex
This will loop through all of the tags. You might want to add code to check it's the one you want to change in case there are multiple tags.
for (var tag in message_tags) {
message_tags[tag].name = "...";
}
For..in solution
Use the for..in javascript statement to traverse your object properties and then act upon those results.

Categories