Javascript Object attribute with '-' doesn't work properly [duplicate] - javascript

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 7 years ago.
I have a JSON response in the following format.
{
"_meta" : {
"next-person-id" : "1001",
"totalPersons" : "1000"
}
}
I am using Angular's $http service to retrieve this and trying to access next-person-id attribute in javascript like the following,
$http.get(url).then(
function(response){
console.log(response._meta.next-person-id);
}
);
But the next-person-id in the response is undefined always. But I'm able to access totalPersons attribute. Is there any problem with getting attributes with '-' character in javascript?

Use bracket notation:
console.log(response._meta['next-person-id']);
A possible alternative is to change the keys to use underscores, so that _meta.next_person_id would work.

You cant write variables using - as it is also a minus sign.
To solve this, use square bracket notation:
console.log(response._meta['next-person-id']);

Yep true, because in JavaScript you can use Latin letters, numbers and $ _ symbols for variables or properties.
If you want to use -, you should escape it with string quotes.
like this
var obj = {
'next-person-id': 2
}
console.log(obj['next-person-id']); // 2
Explanation:
In Global scope - means minus. It tries to subtract person from name. So you will get an error like this:
ReferenceError: name is not defined
In JS you can access to object property in 2 ways
1) Dot nation
obj.property
2) Square bracket nation
obj['property']
Here you need to parse string, so as you know in string you can have any symbols except string quote symbol (it will close the string)
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation

Related

Adding prev to linked list [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 5 years ago.
What is the real difference in using [] and . for accessing array or object properties? Which one to use?
Also why doesn't . operator allow the index property?
Accessing members with . is called dot notation. Accessing them with [] is called bracket notation.
The dot notation only works with property names which are valid identifier names [spec], so basically any name that would also be a valid variable name (a valid identifier, see also What characters are valid for JavaScript variable names?) and any reserved keyword [spec].
Bracket notation expects an expression which evaluates to a string (or can be coerced to a string), so you can use any character sequence as property name. There are no limits to what a string can contain.
Examples:
obj.foo; // valid
obj.else // valid, reserved keywords are valid identifier names
obj.42 // invalid, identifier names cannot start with numbers
obj.3foo // invalid, ""
obj.foo-bar // invalid, `-` is not allowed in identifier names
obj[42] // valid, 42 will be coerced to "42"
obj["--"] // valid, any character sequence is allowed
obj[bar] // valid, will evaluate the variable `bar` and
// use its value as property name
Use bracket notation:
When the property name is contained in a variable, e.g. obj[foo].
The property name contains characters not permitted in identifiers, e.g. starts with a digit†, or contains a space or dash (-), e.g. obj["my property"].
Use dot notation: In all other situations.
There is a caveat though regarding reserved keywords. While the specification permits to use them as property names and with the dot notation, not all browsers or tools respect this (notably older IE versions). So the best solution in my opinion is to avoid using reserved keywords for property names or use bracket notation if you cannot.
†: That's also the reason why you can only use bracket notation to access array elements. Identifiers cannot start with digits, and hence cannot consist only of digits.
You should use . when you know the name of the property
var object = {};
object.property = 'whatever';
, use [] when the name of the property is contained in a variable
var object = {};
var property = 'another-property';
object[property] = 'whatever';
As #DCoder added certain object properties cannot be accessed without using the [] notation because their names break the syntax. E.g. properties named class, default, or data-prop-value
Also why doesn't . operator allow the index property? I really want
full reason. Thank you.
Well if that was possible, consider:
var a = 0.5;
Did you mean the number 0.5 or access the 5 element of the number?
See:
Number.prototype[5] = 3;
0[5] //3
0.5 // 0.5
If you allowed the syntax 0.5 to be equal to 0[5], then how do you know what you mean?
It is however possible to use numbers directly with object literal:
var a = {
0: 3,
1: 5
};
Both dot operator and index(bracket notation) operator are used to access the property of an Object. Generally accessing with dot operator is quite faster because accessing variables by window is significantly slower though. But in case of special character
in the variables, you cannot use dot operator as it will give error. For such cases we need to use index operator and pass the variable name as a string format means underdouble quote otherwise it will give undefined error.
e.g-
var abc = {
font-size : "12px"
}
Using dot operator - abc.font-size; //it will give error (Incorrect)
Using index operator - abc["font-size"]; //12px (Correct)

Is there any ways to make this code shorter to return object? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 5 years ago.
What is the real difference in using [] and . for accessing array or object properties? Which one to use?
Also why doesn't . operator allow the index property?
Accessing members with . is called dot notation. Accessing them with [] is called bracket notation.
The dot notation only works with property names which are valid identifier names [spec], so basically any name that would also be a valid variable name (a valid identifier, see also What characters are valid for JavaScript variable names?) and any reserved keyword [spec].
Bracket notation expects an expression which evaluates to a string (or can be coerced to a string), so you can use any character sequence as property name. There are no limits to what a string can contain.
Examples:
obj.foo; // valid
obj.else // valid, reserved keywords are valid identifier names
obj.42 // invalid, identifier names cannot start with numbers
obj.3foo // invalid, ""
obj.foo-bar // invalid, `-` is not allowed in identifier names
obj[42] // valid, 42 will be coerced to "42"
obj["--"] // valid, any character sequence is allowed
obj[bar] // valid, will evaluate the variable `bar` and
// use its value as property name
Use bracket notation:
When the property name is contained in a variable, e.g. obj[foo].
The property name contains characters not permitted in identifiers, e.g. starts with a digit†, or contains a space or dash (-), e.g. obj["my property"].
Use dot notation: In all other situations.
There is a caveat though regarding reserved keywords. While the specification permits to use them as property names and with the dot notation, not all browsers or tools respect this (notably older IE versions). So the best solution in my opinion is to avoid using reserved keywords for property names or use bracket notation if you cannot.
†: That's also the reason why you can only use bracket notation to access array elements. Identifiers cannot start with digits, and hence cannot consist only of digits.
You should use . when you know the name of the property
var object = {};
object.property = 'whatever';
, use [] when the name of the property is contained in a variable
var object = {};
var property = 'another-property';
object[property] = 'whatever';
As #DCoder added certain object properties cannot be accessed without using the [] notation because their names break the syntax. E.g. properties named class, default, or data-prop-value
Also why doesn't . operator allow the index property? I really want
full reason. Thank you.
Well if that was possible, consider:
var a = 0.5;
Did you mean the number 0.5 or access the 5 element of the number?
See:
Number.prototype[5] = 3;
0[5] //3
0.5 // 0.5
If you allowed the syntax 0.5 to be equal to 0[5], then how do you know what you mean?
It is however possible to use numbers directly with object literal:
var a = {
0: 3,
1: 5
};
Both dot operator and index(bracket notation) operator are used to access the property of an Object. Generally accessing with dot operator is quite faster because accessing variables by window is significantly slower though. But in case of special character
in the variables, you cannot use dot operator as it will give error. For such cases we need to use index operator and pass the variable name as a string format means underdouble quote otherwise it will give undefined error.
e.g-
var abc = {
font-size : "12px"
}
Using dot operator - abc.font-size; //it will give error (Incorrect)
Using index operator - abc["font-size"]; //12px (Correct)

Unable to access JSON property with "-" dash [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
How do I reference a JavaScript object property with a hyphen in it?
(11 answers)
Closed 3 months ago.
I am unable to retrieve a value from a json object when the string has a dash character:
{
"profile-id":1234, "user_id":6789
}
If I try to reference the parsed jsonObj.profile-id it returns ReferenceError: "id" is not defined but jsonObj.user_id will return 6789
I don't have a way to modify the values being returned by the external api call and trying to parse the returned string in order to remove dashes will ruin urls, etc., that are passed as well. Help?
jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).
To access a key that contains characters that cannot appear in an identifier, use brackets:
jsonObj["profile-id"]
In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax
This is the wrong way
json.first.second.third['comment']
and will will give you the 'undefined' error.
This is the correct way
json['first']['second']['third']['comment']
For ansible, and using hyphen, this worked for me:
- name: free-ud-ssd-space-in-percent
debug:
var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]
For anyone trying to apply the accepted solution to HomeAssistant value templates, you must use single quotes if you are nesting in doubles:
value_template: "{{ value_json['internet-computer'].usd }}"
If you are in Linux, try using the following template to print JSON value which contains dashes '-'
jq '.["value-with-dash"]'
It worked for me.

Javascript object property quotes [duplicate]

This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 5 years ago.
Let's say I have the following object:
var VariableName = {
firstProperty: 1,
secondProperty: 2
}
Do I have to wrap the object properties in quotes like this?
var VariableName = {
'firstProperty': 1,
'secondProperty': 2
}
Is this Single quotes in JavaScript object literal the correct answer?
No, you don't need to do that.
The only reasons to quote object-keys are
the property name is reserved/used by the browser/js engine (eg. "class" in IE)
you have special characters or white spaces in your key
so for instance
var VariableName = {
"some-prop": 42, // needs quotation because of `-`
"class": 'foobar' // doesn't syntatically require quotes, but it will fail on some IEs
valid: 'yay' // no quotes required
};
You only have to use the quotes around the property, if the property name is a reserved word (like for, in, function, ...). That way you prevent Javascript from trying to interpret the keyword as a part of the language and most probably get a syntax error.
Furthermore, if you want to use spaces in property names, you also have to use quotes.
If your property names are just normal names without any collusion potential or spaces, you may use the syntax you prefer.
One other possibility that requires quotes is the use of Javascript minifiers like google closure compiler, as it tends to replace all property names. If you put your property names in quotes, however, the closure compiler preserves the property as you coded it. This has some relevance when exporting objects in a library or using an parameter object.
Property names in object literals must be strings, numbers or identifiers. If the name is a valid identifier, then you don't need quotes, otherwise they follow the same rules as strings.
firstProperty and secondProperty are both valid identifiers, so you don't need quotes.
See page 65 of the specification for more details.
For Javascript you usually do not have to use quotes. You may use ' or " if you like, and you must use quotes if there is a clash between the name of your property and a JS reserved word like null. The answer you linked to seems to be correct, yes.
For JSON, you should use " around strings (including object property names)

In JavaScript, what is the difference between a property name in double-quotes ("") and without? [duplicate]

This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 5 years ago.
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
What's the difference between car.manyCars.a and car.manyCars.b in this example?
None whatsoever.
Quotes allow you to specify names which are not valid javascript identifiers, but both a and b are. For example, this wouldn't be legal:
var car = { a*b: "Saab" };
whereas this would be
var car = { "a*b": "Saab" };
As a*b is not a valid identifier.
Note that JSON (which is based on JavaScript) does not allow unquoted names.
Edit
An exception here, as you've noticed, you can use numbers without quoting them, which are not valid javascript identifiers. This is actually rather weird, don't have a good reason for this, probably the opportunity to shorthand the declaration. car.7 won't parse for the same reason, it is not a valid identifier, and you need to use car[7].
As roe said, there's no difference in the end, but it allows to you to use otherwise reserved keywords or invalid identifiers:
var x = { 'a b c' : 1, 'a%#!6!#' : 1};
It probably isn't a bad idea to always use quotes. Different javascript engines consider different things to be reserved. For example, this works fine in a browser, but causes a syntax error in Rhino:
var x = { native : true };
The Mozilla Developer Network has some good information too: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators
Dot notation
some_object.property
property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.
Bracket notation
some_object[property]
property is a string. The string does not have to be a valid identifier; it can have any value, e.g. "1foo", "!bar!", or even " " (a space).

Categories

Resources