jgeerts jgeerts - 2 days ago 4
Javascript Question

Immutable.js nested array updateIn

I want to make use of Immutable's functions to update my structure from this structure but I'm uncertain in how to do it. My tags shouldn't be an array but should become objects just for posting to my REST api.

There are several examples on how to update deep properties and nested arrays, but I want to change values 2 arrays deep.

order: {
createDate: '2016-08-07',
pickupDate: '2017-02-02',
items: [
{
price: '25',
tags: [
'Blue',
'Pants'
]
}
]
}


to this structure

order: {
createDate: '2016-08-07',
pickupDate: '2017-02-02',
items: [
{
price: '25',
tags: [
{
text: 'Blue'
},
{
text: 'Pants'
}
]
}
]
}

Answer

Something like this:

const { fromJS, Map } = require("immutable")

const obj = fromJS({
    order: {
        createDate: '2016-08-07',
        pickupDate: '2017-02-02',
        items: [
            {
                price: '25',
                tags: [
                    'Blue',
                    'Pants'
                ]
            }
        ]
    }
})

const items = obj
    .getIn(['order', 'items'])
    .map((item) => {
        const newTags = item
            .get('tags')
            .map((tag) => ({ text: tag }));
        return item.set('tags', newTags);
    });

const newMap = obj.setIn(['order', 'items'], items);
Comments