0
votes

I am trying to achieve the following javascript code in clojurescript:

const a = {
   "foo": "bar",
   //...
};

let b = {
    ...a,
  //^ what is the clojurescript equivalent for this?
    "newprop": 10,
};

I have tried to assoc-in, thinking it would behave like a clojure map, with no success...

4
If you haven't seen it, be sure to checkout the ClojureScript CheatSheet! cljs.info - Alan Thompson

4 Answers

1
votes

To provide you with another option, you can use goog.object to interact with JavaScript objects in ClojureScript. The following code will work:

(require 'goog.object)

(def a #js {:foo "bar"})

;; Modify `a` inline
(goog.object/set a "newprop" 10) ;; In JS, this is equivalent to a.newprop = 10

If you want to do a shallow copy of a and modify that value, you can use clone (which will behave like the spread operator).

;; Shallow copy a
(def b (goog.object/clone a))

;; Modify the cloned object
(goog.object/set b "newprop" 10)

There's a neat library you can use though to interact with JavaScript objects if you need to do it often: https://github.com/binaryage/cljs-oops

0
votes
(def a {:foo "bar"})
(def b (assoc a :newProp 10))
0
votes

This is really just combining two maps together. That can be done with merge:

(def a {"foo" "bar"})  ; Emulating the constant
(def b {"newprop" 10})

(def c (merge a b))  ; {"foo" "bar", "newprop" 10}
0
votes

My question was not clear enough, I had an object defaultProps coming from an external js library. My goal was to create a new instance of this js object and extending it with new props, and feeding it back to a js function expecting a js object. There was more to it than I first foresaw. I finally managed to do it with some juggling with js->clj and clj->js:

(def b
    (clj->js (assoc (js->clj a) "newprop" 10)))

Thank you for your answers!