How do I reference a JavaScript object property with a hyphen in it?
Look at the comments. You will see that for CSS properties, the key notation is not compatible with a number of properties. Using the camel case key notation therefore is the current way:
obj.style-attr // would become
obj["styleAttr"]
Use key notation rather than dot
style["text-align"]
All arrays in JavaScript are objects and all objects are just associative arrays. This means you can refer to a place in an object just as you would refer to a key in an array.
arr[0]
or the object
obj["method"] == obj.method
A couple things to remember when accessing properties this way:
they are evaluated so use strings unless you are doing something with a counter or using dynamic method names.
This means obj[method] would give you an undefined error while obj["method"] would not
You must use this notation if you are using characters that are not allowed in JavaScript variables.
This regex pretty much sums it up:
[a-zA-Z_$][0-9a-zA-Z_$]*
Referencing object's property name with hyphen
You Could use data["foo-bar"]
Instead.
Object key name with dash
You have to put the key in quotes
let myObject = {
'one-property': 'assignee'
}
how to access an object property that has dash(-) in it
eachItem["team-1"] this should be fine. if its not, could be a different problem
const hero = {
"spider-man" : 1
}
console.log(hero["spider-man"])
Are dashes allowed in javascript property names?
no. the parser will interpret it as the subtract operator.
you can do settings['background-color']
.
Referencing an object property that has dashes in the name
Your approach with the curly braces wasn't too wrong, but you need a string between the braces:
var_dump($child->{'item--1'});
How to use hyphen while passing object property as an argument
The code is reading it as section.section - id (undefined - undefined = NaN) try
<div *ngFor="let section of sections (trackScrollLeave)="leave(section['section-id'])"></div>
resource on bracket property accessors - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Use of hyphenated property keys for element.style
The documentation links to the relevant specification.
An HTMLElement.prototype.style
getter results in a CSS2Properties
object which inherits from CSSStyleDeclaration
, the specification of which has a few relevant paragraphs about camel-cased properties:
The camel-cased attribute attribute, on getting, must return the result of invoking
getPropertyValue()
with the argument being the result of running the IDL attribute to CSS property algorithm for camel-cased attribute.Setting the camel-cased attribute attribute must invoke
setProperty()
with the first argument being the result of running the IDL attribute to CSS property algorithm for camel-cased attribute, as second argument the given value, and no third argument. Any exceptions thrown must be re-thrown.
… and about dashed properties:
The dashed attribute attribute, on getting, must return the result of invoking
getPropertyValue()
with the argument being dashed attribute.Setting the dashed attribute attribute must invoke
setProperty()
with the first argument being dashed attribute, as second argument the given value, and no third argument. Any exceptions thrown must be re-thrown.
The mentioned IDL attribute to CSS property algorithm is a way of normalizing a property key before getting or setting the actual key and value. Therefore, the equivalence of the camel-cased and hyphenated version of properties is specified.
But there's a single exception: float
. Because ECMAScript editions 1, 2, and 3 disallowed reserved words as property names, using element.style.float
was impossible; since the 5th edition it's possible. The usable property is called cssFloat
and the spec has this to say about cssFloat
:
The
cssFloat
attribute, on getting, must return the result of invokinggetPropertyValue()
withfloat
as argument. On setting, the attribute must invokesetProperty()
withfloat
as first argument, as second argument the given value, and no third argument. Any exceptions thrown must be re-thrown.
However, older browsers don't follow this specification (or convention before the spec existed) very well. See Where do the JavaScript style
property names come from?: old Internet Explorer versions use styleFloat
instead of cssFloat
.
CSS didn't always have a specification; many parts were underspecified or simply unspecified and relied on conventions among browser vendors. It's not easy to accurately find out the implementation reality of this feature, but after some “Internet history” digging, I found:
According to the compatibility table for CSSStyleDeclaration
, Internet Explorer ≤8 didn't support it (properly), but all other browsers did since the beginning.
The current CSSOM specification remained unchanged in this part since the beginning (September 2015).
A previous version of the specification had a complete table to translate properties from one form to the other, but the property normalization remained the same (July 2011).
A specification which goes back to August 2001 has one relevant passage about getting and setting properties and a table of all camel-cased CSS properties implemented on the same interface. The passage is about CSS2Properties
and says:
The
CSS2Properties
interface represents a convenience mechanism for retrieving and setting properties within aCSSStyleDeclaration
. The attributes of this interface correspond to all the properties specified in CSS2. Getting an attribute of this interface is equivalent to calling thegetPropertyValue
method of theCSSStyleDeclaration
interface. Setting an attribute of this interface is equivalent to calling thesetProperty
method of theCSSStyleDeclaration
interface.
getPropertyValue
and setProperty
do accept the hyphenated CSS properties in this version, and, as the quote says, “the attributes of this interface correspond to all the properties specified in CSS2”. However, it seems that the exact correspondence is implied; i.e. the fact that fontSize
maps to font-size
, or that they're supposed to yield the same result, may be underspecified. It also seems to imply that "fontSize"
is an acceptable argument to getPropertyValue
, which it isn't.
Furthermore, the specification only was a proposed recommendation shortly before that (i.e. before 13 November, 2000), and in terms of conformance to the DOM Level 2 CSS spec, this CSS2Properties
interface was optional:
The interface found within this section are [sic!] not mandatory.
It doesn't sound as if it's very likely that browsers from the early 2000s support this equivalence between hyphenated and camel-cased CSS properties.
how to use a object key with " - " in the middle
While defining the array media-metadata
inside obj
it should be wrapped in ""
and when mapping over it then you need to use []
like
const obj = {
approved_for_syndication: 1,
caption: "",
copyright: "",
"media-metadata": [{
name: "test1"
}, {
name: "test2"
}, {
name: "test3"
}],
subtype: "photo",
};
const result = obj["media-metadata"].map((o) => o.name);
console.log(result);
How do I correctly include a dash in an object key in javascript?
jQuery.post("http://mywebsite.com/", {"array-key": "hello"});
should be correct. If this doesn't work, the issue is not with your request.
Related Topics
Remove Whitespace Inside Json Object Key Value Pair
How to Have Multiple Buttons of Same Id Value and When Click on Any Button the Pop-Up Should Come
React-Router Urls Don't Work When Refreshing or Writing Manually
How to Remove Special Character from Json Without Parsing
Multiple Key Names, Same Pair Value
How to Open a Url Link from JavaScript Inside a Google Apps Script HTML Google Site Gadget
Close Window Automatically After Printing Dialog Closes
How to Get Field Value on Change for Formitem in Antd
Javascript: Open Several Urls With One Button Click
Center Content Vertically on Vuetify
How to Insert Dashes Between Each Two Even Digits of a Specific Number
How to Clear Browsing History Using JavaScript
Expected to Return a Value At the End of Arrow Function Array-Callback-Return on Filter Function
Changing the Browser Zoom Level
How to Specify a Single File to Be Seed Only
How to Extract the User Name from an Email Address Using JavaScript