Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to combine two js.Dynamic objects

Tags:

scala.js

Say I have

val obj1 = js.Dynamic.literal(attr1 = "x")
val obj2 = js.Dynamic.literal(attr2 = "y")

and I would like to combine obj1 and obj2 to yield and object of

{attr1 = "x", attr2 = "y"}

Does js.Dynamic have a method to yield such a combination?

like image 585
user79074 Avatar asked Oct 22 '25 05:10

user79074


1 Answers

There is no existing method doing that. In ES6 there is Object.assign, but it is not supported in IE.

I recommend re-implementing it in Scala.js:

def mergeJSObjects(objs: js.Dynamic*): js.Dynamic = {
  val result = js.Dictionary.empty[Any]
  for (source <- objs) {
    for ((key, value) <- source.asInstanceOf[js.Dictionary[Any]])
      result(key) = value
  }
  result.asInstanceOf[js.Dynamic]
}

And now you can simply do

mergeJSObjects(obj1, obj2)
like image 163
sjrd Avatar answered Oct 24 '25 23:10

sjrd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!