Mapping a dot notation key in an object? - javascript

I have an object like this:
let object = {
seniority: 'director_level',
'address.long_form': 'Phoenix, AZ, United States'
}
when I go to print address.long_form like this I get an error.
console.log(object.address.long_form)
How do get the value for 'address.long_form'?

Since address.long_form is in string, you cannot use dot notation instead use this
console.log(object['address.long_form'])

It will work like this: object["address.long_form"], but just don't use dots in object indexes.

You can still extract it but you can't use the literal notation, you need to use the [] notation in order to get past the ambiguity.
i.e.
console.log(object['address.long_form'])
Of course better would to just avoid keys in that form, but depends on your data.

Related

Quotes as array index [""] (Javascript)

I found this notation in a javascript code:
this.numbers[""].x
I can't understand what the apices mean. What do they do?
It means that numbers is an object which contains a key which is the empty string. Using [''] will access the property of the object which is the empty string (and then .x will access the x property inside it).
It sounds very strange, and it is, but it's syntactically legal to construct such a thing:
const numbers = {
'': {
x: 'valueOfX'
}
};
console.log(numbers[''].x);
(If you ever see this sort of thing in code that you have control over, I'd suggest considering refactoring it to be less confusing)

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"])

Get nth element of a key in an object

I'd like to return the third node (hello3.com) of the key hello.com in javascript object.
nodes = {
"hello.com":
{
id:"hello1.com",
id2:"hello2.com",
id3:"hello3.com"
}
}
I know that I can fetch all the key/values like this:
newobject = nodes["hello.com"];
but how would I get the third. I'm aware that you can't count on the order in an object. If not, can I pull just the third by maybeb id3.
You answered your own question when you said that you can't count on the properties of an object to be in any certain order. If your properties are sequential in nature (your properties were counting up in your example), then I would suggest trying to use an Array.
nodes = {
"hello.com": [
"hello1.com",
"hello2.com",
"hello3.com"
]
};
In the above example, you would access the 3rd property with
nodes["hello.com"][2]
The double bracket notation is because "hello.com" is in quotes to allow a . in the name. If the key didn't require quotes, like helloCom as an example, you could use
nodes.helloCom[2]
Beyond this, if you name your keys sequentially, then you can impose an "order". It's not that any property is literally before or after another, but rather that you have informed yourself of what order YOU intend them to be.
You can try this,
nodes = {
"hello.com": {
id: "hello1.com",
id2: "hello2.com",
id3: "hello3.com"
}
}
console.log(nodes["hello.com"]["id3"]);
Use:
nodes['hello.com'].id3 or nodes['hello.com']['id3']
Both are corrent way to get id3 data from given object
BY INDEX :
About accessing by index, you can not achieve it directly. the closest you can get is array of keys but that also do not guarantee the order of keys returned. See this answer provided on other thread.
for (var i in nodes["hello.com"]) { console.log(i);//logs id,id2,id3 };
BY NODENAME:
nodes["hello.com"] returns object. You can use key to access the value by
1) using dot notation:
nodes["hello.com"].id3
2) or by bracket notation
nodes["hello.com"]["id3"]
Try one of the following expressions
nodes["hello.com"]["id3"]
or
nodes["hello.com"].id3

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")

Point the right key with a variable of a json array

I get the following json array from an api:
response = {"base":"USD","date":"2015-11-05","rates":
{"AUD":1.3997,"BGN":1.7971,"BRL":3.8008}}
I get that from the following http query:
$http.get(url).success(function(response){
let assume that
quote = "AUD";
How can I point to the AUD value of rates in response (i.e. rate = 1.3997)?
$scope.rate = response.rates.quote;
does not work...
this is called accessing property value of an object this is how we do it
var quote = 'AUD'
var response = {"base":"USD","date":"2015-11-05","rates":
{"AUD":1.3997,"BGN":1.7971,"BRL":3.8008}}
object = JSON.parse(JSON.stringify(response))
document.write(object.rates[quote])
If you use
rates.quote
This means that quote is a property of rates object which is not;
The value of quote is the property of rates
Try like this
$scope.rate = response.rates[quote];
This is one of those times when you have to use the square bracket notation instead of dot notation even though they are usually interchangeable. You can only use dot notation when you know the real name of the property. When you are using a variable as a placeholder you have to use square brackets.
Dot notaion has its limit, use brackets as others already suggested.
The dot notation is:
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Categories