Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable.Js - Add new property in Map

So let's say that I make a REST API call and receive a JSON in this format:

{
    "plan": {
        "createdDate": "05/04/2017",
        "location": {
          "city": null
          "state": null
        }
        "family": null
    }
}

And within in my reducer, make the JSON as an immutable as so:

Immutable.Map(Immutable.fromJS(action.json))

Along the way, is it possible to add properties under family?

For instance, when I am submitting a form to a server, ideally I like to send something like this:

{
    "plan": {
        "createdDate": "05/04/2017",
        "location": {
          "city": null
          "state": null
        }
        "family": {
          "father": "Homer",
          "mother": "Marge",
          "son": "Bartholomew"
        }
    }
}

Or do I have to initialized first to have those properties under family from the start?

like image 409
Alejandro Avatar asked Jun 10 '26 19:06

Alejandro


1 Answers

You can follow this way via mergeDeep of Immutable:

const { fromJS } = require('[email protected]')

const initialState = fromJS({
    "plan": {
        "createdDate": "05/04/2017",
        "location": {
          "city": null,
          "state": null
        },
        "family": null
    }
})

const newState = initialState.mergeDeep({
    "plan": {
        "family": {
            "father": "Homer",
            "mother": "Marge",
            "son": "Bartholomew"
        }
    }
})

console.log(newState.toJS())

You will got this result

{
    "plan": {
        "createdDate": "05/04/2017",
        "location": {
          "city": null,
          "state": null
        },
        "family": {
            "father": "Homer",
            "mother": "Marge",
            "son": "Bartholomew"
        }
    }
}

Hope this can help you for solving this same issue with me, I was succeed!

like image 67
Quynh Nguyen Avatar answered Jun 13 '26 10:06

Quynh Nguyen



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!