Dynamically assigning properties on plain javascript objects - tricky
See original GitHub issueHi,
I was hoping to be able to convert a [<String->Object>*]
to a properties of a plain javascript object, but bumped into some problems.
So the first attempt is:
dynamic JSObject {}
JSObject? toObj([<String->Object>*] props) {
dynamic obj;
dynamic {
obj = dynamic [];
}
for (k->v in props) {
dynamic {
obj[k] = v;
}
}
dynamic {
return obj;
}
}
but that didn’t work, I get an error Expression cannot be assigned
for the obj[k] = v;
line. Next I try to replace that line with a bit of javascript:
eval("(function(o,k,v){o[k]=v})")(obj, k, v);
Now I instead get the error (same error as in #5808 btw):
The GenerateJsVisitor caused an exception visiting a InvocationExpression node: "java.lang.NullPointerException" at com.redhat.ceylon.compiler.js.InvocationGenerator.positionalInvocation(InvocationGenerator.java:182)"
Finally I put the eval-generated function in a temporary variable and this works:
dynamic set = eval("(function(o,k,v){o[k]=v})");
set(obj, k, v);
I’m guessing all of my approaches should work. Also if you happen to know a pre-existing function to does what I’m doing, let me know 😃
Issue Analytics
- State:
- Created 8 years ago
- Comments:10 (10 by maintainers)
Top Results From Across the Web
Accessing an object property with a dynamically-computed ...
There are two ways to access properties of an object: ... Some more info on why this is possible: JS objects are associative...
Read more >A Cool Way to Add Dynamic Object Properties in JavaScript
A Cool Way to Add Dynamic Object Properties in JavaScript. A simple and concise way to add properties to an object conditionally.
Read more >Working with objects - JavaScript - MDN Web Docs - Mozilla
A JavaScript object has properties associated with it. Object properties are basically the same as variables, except that they are associated ...
Read more >Why is dynamically adding properties slow in JavaScript?
JS gives an ability to add properties to the object after it was created. It gives a lot of freedom but has a...
Read more >How to Set Dynamic Property Keys with ES6 - Samantha Ming
How to Set Dynamic Property Keys with ES6. Previously, we had to do 2 steps - create the object literal and then use...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
with #4148 I added support for the
x[foo]=bar
syntax and it can now be used on plain JS objects inside dynamic blocks.This gist could become the beginning of a new
ceylon.interop.js
module…