5

I'm just starting with immutable.js and I'm having trouble figuring out how to set a new property on objects within an array. I'm having trouble finding any examples in the docs of this kind of change.

I'm basically just trying to take change this:

[{ 
  gitInfo: {id: 8001, host: '', …},
  module: {id: 24875, name: "blah", …}
}...]

to this:

[{ 
  gitInfo: {id: 8001, host: '', …},
  module: {id: 24875, name: "blah", isStared: true …}
}...]

So w/out immutable.js I would have something like:

function markModules(modules) {
    modules.map( (module) => {
      module.module.isStarred = false;
      if (contains(this.props.stars, module.module.id)) {
        module.module.isStarred = true;
      }
    })
    return modules;
  }

I'm assuming I need something like set() with a List, but again, I'm not finding any examples how to do this.

Thanks for any tips or links to examples.

1 Answer 1

6

You'd do it the same way you would without Immutable.js (.map).

const data = Immutable.fromJS([{ 
  gitInfo: {id: 8001, host: ''},
  module: {id: 24875, name: "blah"}
}, { 
  gitInfo: {id: 6996, host: ''},
  module: {id: 666, name: "wef"}
}]);

const transformed = data.map((x) => {
    return x.get('module').set('isStarred', true);
})

transformed.toJS() === [
  {
    "id": 24875,
    "name": "blah",
    "isStarred": true
  },
  {
    "id": 666,
    "name": "wef",
    "isStarred": true
  }
]

And if you want to put the extra logic in there:

function markModules(modules) {
  return modules.map((module) => {
    const isStarred = contains(this.props.stars, module.getIn(['module', 'id']));
    return module.setIn(['module', 'isStarred'], isStarred);
  })
}

The key is to turn your if statements into values/functions that return values instead of updating the data structure.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.