How to call function using bracket notation in node js - javascript

I know we can access data using dot notation and bracket notation but here if I access faker data using bracket notation I can't access that data. Is there any way to access data using bracket notation?
var faker = require("faker");
console.log(faker.name.findName()); // Output: any name.
console.log(faker["name.findName"]()); // Output: TypeError: faker.name.findName is not a function

The problem is that
faker["name.findName"]
would try to access a property called "name.findName" on the faker-object.
In order to access findName using bracket-notation, you need to change it to:
console.log(faker["name"]["findName"]());

You shouldn't use bracket notation to return functions.
console.log(faker["name"].findName())
or if you really just want to use brackets, try
let _findName = faker["name"]["findName"];
console.log(_findName());

Related

What is this "[]" here doing?

Below is an extract from my textbook.
I have a question about the use of [] here in window.history[type](). I can tell that it's separating the object name(window) and the variable(type) so that they can be recognized as separate things but is there a name for this use of []? I performed a google search but nothing came up.
$(function() {
//omitted
['back', 'forward'].forEach(function(type) {
$('.' + type).click(function() {
window.history[type]();
});
});
});
This is property/method access using bracket notation.
In Javascript, you can access the properties of an object using the dot notation:
myObj.prop
Or the bracket notation:
myObj['prop']
When you dynamically construct the properties, however, you have no choice but to use bracket notation:
window.history['forward']()
is the same as
window.history.forward()
Here you are iterating on the forward and back properties, and the bracket notation is used to call the functions from their string names on window.history.
Here is the doc linked by #Teemu

Passing an Object as an Argument in Javascript - But not simply an Argument but an argument built from variables

I am passing an object to a function. Simplified example below:
countyInfo(sales.NY2008);
The object is:
{countyName:"Albany",percentage:0.864789889,percentageComparison:40.18903649,sales:1222},
{countyName:"Allegany",percentage:0.789529462,percentageComparison:27.98874729,sales:149},
{countyName:"Broome",percentage:1.009475302,percentageComparison:63.64364553,sales:880},
{countyName:"Cattaraugus",percentage:0.874885092,percentageComparison:41.82554597,sales:276},
{countyName:"Cayuga",percentage:0.801267677,percentageComparison:29.89160156,sales:268},
{countyName:"Chautauqua",percentage:0.830185925,percentageComparison:34.5794701,sales:455},
{countyName:"Chemung",percentage:0.744919757,percentageComparison:20.75717391,sales:272},
{countyName:"Chenango",percentage:1.191003494,percentageComparison:93.07074993,sales:242},
{countyName:"Clinton",percentage:0.767315265,percentageComparison:24.38765663,sales:265},
{countyName:"Columbia",percentage:0.83461736,percentageComparison:35.29783949,sales:260},
{countyName:"Cortland",percentage:1.144086442,percentageComparison:85.46513794,sales:234},
It works beautifully.
Now I would like to compose this parameter from variables.
var getLocation = "NY";
var getYear = "2008";
var getParameter= getLocation + getYear;
countyInfo(sales.getParameter)
It doesn't work as I'm passing a string. But how can this be done?
Just change your code to use bracket notation to access object property instead of dot notation
var getLocation = "NY";
var getYear = "2008";
var getParameter= getLocation + getYear;
countyInfo(sales[getParameter]);
Dot notation:
Property identifies can only be alphanumeric (and _ and $)
Propertyidentifiers cannot start with a number.
Property identifiers cannot contain variables.
OK — obj.prop_1, obj.prop$
Not OK — obj.1prop, obj.prop name
Bracket notation:
Property identifiers have to be a String or a variable that
references a String.
It is okay to use variables, spaces, and Strings
that start with numbers
OK — obj["1prop"], obj["prop name"]
For Detailed explanation refer this --
https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781
Since sales seems to be an object, you can use index notation to access a member.
That is, sales.NY2008 is equivalent to sales["NY2008"].
So, simply do
countyInfo(sales[getLocation + getYear]);

Bad character in json response angular 2

I've retrieved a JSON response from an external API and one of the variable names begins with a # character, so the JSON variable looks like this #text. Unfortunately angular doesn't know how to handle this variable, is there any way delete the # so that the data assigned to the identifier is usable.
In order to reference a property that does not follow the rules for a properly formatted identifier, you must use bracket notation instead of dot notation for the property accessor:
var object = JSON.parse('{"#text":"https://lastfm-im...png","size":"extralarge"}')
console.log(object['#text'])
you cam modifide the response - loop throw it wite map- and chenge the object key -see here:
JavaScript: Object Rename Key
You can use square bracket notation instead of dot notation. like (Object mutation is highly not recommended)
//to access it u can use square bracket notation like k["objectname"]
let k = {"#test":"some data"}
alert("data is "+k["#test"])

Use hasOwnProperty with dot notation

I have one object var tree={} with attribute tree.leaves.leaf={}.
When I perform tree.hasOwnProperty("leaves.leaf") its giving false .
Can I use dot function inside hasOwnProperty() function? How to do it?
If you want to create a property with key leaves.leaf, then you need to use bracket notation
tree["leaves.leaf"]={}
now tree.hasOwnProperty("leaves.leaf") will give true.
You have to use something like below
var tree = {}
tree["leaves"]={}
tree["leaves"]['leaf'] = {}
tree.leaves.hasOwnProperty("leaf")

Get JSON attribute value by paasing attribute name via "var" in Javascript

In json can we get attribute value by passing variably value . Means
It works for me when "name" attribute exists in my "returnData" json object
// It works
var getColValue= returnedData[0].name
but it give undefined error
// It Not works
var refVar ="name";
var getColValue= returnedData[0].refVar;
var getColValue= returnedData[refVar];
should work. Please give it a try.
Use square bracket notation:
returnedData[refVar];
In other words, these two are basically equivalent:
returnedData["name"] === returnedData.name
Note that, using square-bracket notation allows you to set/get property names that wouldn't be valid with the dot notation. Eg, returnedData.some-prop is not a valid Javascript object, but returnedData["some-prop"] is.

Categories