Retrieve JSON data with string variable - javascript

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.

Related

Read data with dash operator using React

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

Is Object.entries vulnerable to object injection attacks?

Let's say I want to build a table out of the key/values in a hash (not what I was doing, but similar enough). This is some code that would be delivered as part of a web page. The first version I wrote was like so:
let table = '';
Object.keys(foo).forEach(k =>
// eslint-disable-next-line security/detect-object-injection
table += `||${k}|${foo[k]}||\n`
);
This triggered eslint's object injection error (which gives a lot of false positives but this object isn't coming from client input so it seems safe). But I wanted to try and refactor to get rid of the object injection issue:
let table = '';
Object.entries(foo).forEach(kv => table += `||${kv[0]}|${kv[1]}||\n` );
That got rid of the security/detect-object-injection problem according to eslint. But I wanted to make sure and I can't find any discussion of how to work around this on here.
Is Object.entries better for iterating a hash (and values) vs. Object.keys when it comes to object injection?
The two methods are equivalent. The difference is that in the second case, simple static analysis can determine that there's no object injection, since there's no use of a variable in the object index. In the first case, eslint can't tell that k is a safe index, but we can tell it easily because Object.keys() doesn't return user input.
The warning in the first version is a false positive. Object injection only occurs when the key comes from an untrusted source, since it allows them to access any property of the object. But if you're generating the list of properties in your code, it's not injection. The false positives happen because eslint doesn't know where k comes from in foo[k], so it assumes the worst.
Read The Dangers of Square Bracket Notation
If your intent is to process all the properties, then there's no object injection when you get k from Object.keys(). And for the same reason, there's no object injection when you use Object.entries(), since it's getting the same keys and values.

chai things - comprehensive list of should() methods

I'm looking for a comprehensive list of methods you can call on a decorated object using the chai-things library for chai.js
so, for example :
myObject.should.METHOD_NAME.
What are all of the valid METHOD_NAMEs that can be called in the above statement. If valid method names are based on object type, is there a table listing methods per object type available ?
for example, here are some of the methods available:
an
change
changes
contain
contains
decrease
decreases
include
includes
increase
increases
length
not
be
eql
Here is another example, if you call 'increase' on an array assertion you get an error, whereas if you call 'contain' it's okay. I'm seeking the documentation that describes these rules.
thanks
All of the methods for should are available in the docs under "Expect / Should" (http://chaijs.com/api/bdd/), for example here's the docs for contain (which is an alias of .include):
.include(value)
#param{ Object | String | Number }obj
#param{ String }message_optional_
The include and contain assertions can be used as either property based language chains or as methods to assert the inclusion of an object in an array or a substring in a string. When used as language chains, they toggle the contains flag for the keys assertion.
expect([1,2,3]).to.include(2);
expect('foobar').to.contain('foo');
expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');
The docs show examples using the expect(foo).to... syntax, but expect(foo).to. and foo.should are completely interchangeable.
If you want you can also look at the source code - all of the core assertions are in one file; chai/lib/core/assertions.js - they're constructed using addMethod but each one comes with docs (the docs are used to generate the website) so it should be easy enough to read.
Every method is available from .should - but there are some special "properties" to help form approximations of english sentences, they don't do anything but they can be used to chain an assertion - these are
to
be
been
is
that
which
and
has
have
with
at
of
same
(So if you really wanted to, you could write 'a'.should.to.be.been.is.that.which.and.has.have.with.at.of.same.equal('a') - and this would have the same effect as 'a'.should.equal('a'))

issue handling property containing brackets in handlebar

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.

Avoiding duplicate JS object properties from a single assignment operation?

I am running a script on a large dataset to expand existing information. e.g:
...
{
id : 1234567890
},
{
id : 1234567891
},
...
becomes
...
{
id : 1234567890,
Name : "Joe"
},
{
id : 1234567891,
Name : "Bob"
},
...
I am doing this via the following code:
for(var cur in members)
{
curMember = members[cur];
// fetch account based on curMember.id to 'curAccount'
if(curAccount != null)
{
curMember.DisplayName = curAccount.DisplayName;
}
}
For the most part, this works as expected. However, once in a while (in the order of tens of thousands of entries), the result looks like this:
...
{
id : 1234567891,
Name : "Bob",
Name : "Bob"
},
...
I now have data which is in an invalid format and cannot be read by the DB, since duplicate property names doesn't make sense. It is occurring for random entries when the script is re-run, not the same ones every time. I need either a way to PREVENT this from happening, or to DETECT that it has happened so I can simply reprocess the entry. Anyone know what's going on here?
EDIT: After further investigation, the problem appears to occur only when the objects being modified come from a MongoDB query. It seems that if code explicitly sets a value to the same element name more than once, the field will be duplicated. All elements of the same name appear to be set to the most recently specified value. If it is only assigned once as in my original problem, it is only duplicated very rarely. I am using MongoDB 2.4.1.
Got it all figured out. MongoDB has a bug up to shell version 2.4.1 which allows duplicate element names to be set for query result objects. Version 2.4.3, released just this Monday, has a fix. See https://jira.mongodb.org/browse/SERVER-9066.
I don't really get your problem. If you apply identical property names to an object in ECMAscript, that property will just get overwritten. The construct in your snippet, can never be exist in that form on a live-object (excluding JSON strings).
If you just want to detect the attempt to create a property which is already there, you either need to have that object reference cached beforehand (so you can loop its keys) - or -
you need to apply ES5 strict mode.
"use strict";
at the top of your file or function. That will assure that your interpreter will throw an exception on the attempt to create two identical property keys. You can of course, use a try - catch statement to intercept that failure then.
Seems like you cannot intercept errors which get thrown because of strict mode violation.

Categories

Resources