user79074
user79074

Reputation: 5270

Is it possible to combine two js.Dynamic objects

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?

Upvotes: 4

Views: 486

Answers (2)

arinray
arinray

Reputation: 216

I put the same question to the scala.js forums and was pointed to js.Object.assign

Upvotes: 0

sjrd
sjrd

Reputation: 22085

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)

Upvotes: 8

Related Questions