This seems to be very silly to me but I am having this problem. Can anybody help me with this.
So, I have an API that I am fetching some data and seems that the API response has a data format like this:
start-time:2323232
end-time:2332323
Now, when in my react rendering component, I am trying to display the data like this:
{data.start-time}
I am actually getting an error saying that time is undefined. Are there any rules that we cannot read/display data in JSX with - separator or something like that. Or, Does anybody know how can I solve that problem. Any helps would be highly appreciated.
You cannot use start-time as an identifier. you need to use square brackets to access the property in this case
data["start-time"]
For further reference Object property accessors
You can only use the dot notation if the property name is a valid JavaScript identifier.
In JavaScript, identifiers are case-sensitive and can contain Unicode letters, $, _, and digits (0-9), but may not start with a digit.
Properties that are not valid identifiers must be accessed through the bracket notation.
const data = { name: "stopwatch", "start-time": 2323232, "end-time": 2332323 };
console.log(data.name); // <- valid identifier
console.log(data["start-time"]); // <- invalid identifier
Related
I have a form DOM element:
var virDom = document.getElementsByTagName("form")[0];
virDom has two fields with IDs creditId and pwdId... I can access virDom.creditId without any issue, but virDom.pwdId.. is failing with a syntax error, because of the periods contained in the name.
How can I access such properties?
Use bracket notation:
virDom['creditId']
virDom['pwdId..']
This applies to any object, and it is particularly useful for non-identifier-safe characters and also for accessing keys that you may not know ahead of time.
For a nested object with a special character like below,
var details = {"name-details": {"first-name": "Kiran"}}
use
console.log(details["name-details"]["first-name"])
I try to use the coinranking api from rapid api but i get a error when a i went to display the 24h volume of a cryptocurrency.
the data is display like this:
Object
data:
coin:
24hVolume: "21504479215"
allTimeHigh: {price: '68763.41083248306', timestamp: 1636502400}
but when i type cryptoDetails?.coin.24hVolume
I got a error that say: An identifier or keyword does not follow a numeric identifier.
How i can override this?
Numeric identifiers are not allowed in JavaScript. However, you could access to object properties using Bracket Notation.
In the object[property_name] syntax, the property_name is just a string or Symbol. So, it can be any string, including '1foo', '!bar!', or even ' ' (a space).
Like this.
obj.data.coin['24hVolume']
I'm developing custom field plugin for Jira Cloud in React.
I have a variable cfDate1 which is stores custom field id as a string like customfield_10072.
So I want to reach the time data inside my custom field id.
Let's say my data is in jsonData variable.
I try to reach with jsonData.fields.[cfDate1] but I get Error: Identifier expected.
I searched a few but I think I couldn't find the right keywords to get some solutions.
Is there anyone can help me to figure it out. I need to learn how to reach json data in my json query with a string variable. Thanks already!
JSON Format (jsonData):
{
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations,customfield_10010.requestTypePractice",
"id": "10008",
"self": "https://alimert.atlassian.net/rest/api/2/issue/10008",
"key": "SP-1",
"fields": {
"statuscategorychangedate": "2021-10-11T12:17:41.291+0300",
"customfield_10072": "2021-01-13T02:00:00.000+0300",
"customfield_10073": "2021-01-26T06:30:00.000+0300",
"customfield_10075": "2021-10-14",
"customfield_10076": "2021-10-15" }
It has to be jsonData.fields[cfDate1] and not jsonData.fields.[cfDate1].
There are four ways to access a property of an object1:
Syntax
Dynamickey
Optionalchaining
.
[]
?
Equivalents2
obj.xyz
No
No
Yes
No
No
obj['xyz']
obj[key]
Yes
No
No
Yes
No
-
obj?.xyz
No
Yes
Yes
No
Yes
obj == null ? obj.xyz : undefinedobj == null ? obj['xyz'] : undefined
obj?.[key] ⚠️
Yes
Yes
Yes ⚠️
Yes
Yes
obj == null ? obj[key] : undefined
As you can see in this table, in most cases you use either . (for static keys) or [] (for dynamic keys).
Optional chaining adds a ?. However, in the case of optional chaining and a dynamic key, the possibly unexpected syntax of ?.[] is used which has both . and []3. Note that this is only the case with optional chaining - without optional chaining, the syntax .[] is not valid.
1: There is also Reflect.get(obj, key), and you could stretch that definition to count something involving walking the prototype chain, calling Object.getOwnPropertyDescriptor and accessing value or get as well, if you really wanted to. But for a beginner, these would be, if anything, more of academic interest and rather confusing to include in a list of property access methods for everyday use.
2: For optional chaining, the shown equivalents only apply to the case of no further level of chaining (e.g. obj?.xyz but not obj?.xyz.abc). An additional - quite useful - property of the optional chaining operator is that it stops evaluation of the rest of the expression entirely in case the left-hand side is nullish, so that you can write obj?.xyz.abc instead of obj?.xyz?.abc without an error Cannot read properties of undefined (reading "abc"). With the shown equivalent that wouldn't work.
3: The reason for this slightly awkward syntax is that optional chaining was added to the language only recently, and ?[] couldn't have been used due to ambiguity with the ternary operator and added difficulty in writing parsers to handle this situation. The same goes for ?.(). See FAQ in the optional chaining proposal for more information.
var jsonString = '{"DeviceId":3,"results":{"1":"[{\"x\":513,\"y\":565,\"width\":175,\"hight\":208}]"}}';
var message = JSON.parse(jsonString);
I got an error saying Unexpected token u in JSON at position 0
at JSON.parse.
Could you please guide me what's wrong?
THanks in advance!
At the last few characters looks wrong. The :212 has no sense as the value (that long array) for key "1" was already set, so that later :212 looks weird
Also enclosing it in single quotes it makes that all be like a huge string, and not as an array structure.
See Results key as value contains a sub array which contain "1" key which as value contains a string enclosing another json array (but escaped as plain string, so no structurally accesible for the main object . But that string if post -processed the :212 is paired to what? , no key, no comma neighter , to the precedent whole array which already was the value, not the key?. Anyway weird.
In your JSON string, there is wrong something with ":212", as it's not valid JSON, because it doesn't have any property that it's mapping the value for. For example, you are mapping values for width and height with properties keys. But for "212", there is no property.
Here is the above JSON formatted:
var jsonString = '{"DeviceId":"3","results":{"1":"[{\\"x\\":513,\\"y\\":565,\\"width\\":175,\\"hight\\":208}]"}}'
var message = JSON.parse(jsonString);
If you want to format the results, you can do to it, there is no error on it:
JSON.parse(message.results['1'])
Here is the JS Bin link for above code: https://jsbin.com/fiyeyet/edit?js,console
Just an advice
Professional code is all about proper spacing, proper identation , proper commenting, don't try to write down all within one single line, structure it VISUALLY nice to see nice to read nice to comprehend, and you will be approved in most jobs.
Hint: declare a normal array/object , convert it to json string using the proper function, then use the string variable returned by the function to test your code or whatever doing. That way, you can write down in the source really nice the structure.
I am trying to find a way to solve a weird property issue serve by server . For some reason server have to send some property in format like propertyname[] so when I have to get the value of the property containing [] is giving me parsing errors
propertyname[] is an array
{{#if this.propertyname[].length}}
...some stuff in here
{{/if}}
there is no way I can read this weird property or maybe I am missing some basic thing in here . any suggestion will be appreciated.
Actually handlebars allows you reference a property that is not a valid identifier such as ! [ # # + * -, just use segment-literal notation to access a invalid property:
this.[propertyname{}] // it equals to this['propertyname{}']
Unfortunately, this method works on the premise that you don't use ']' in a path literal.
I think that change the property name (maybe use other character) or updated the data structure in the front end are possible way to solve this problem.