0

I have below JSON and wanted to update the value depending on Aid, Bid and Cid using Immutable.js

e.g. Below input provided. Aid= A, Bid = 1, Cid= 4, NewValue = 'FOUR' If above input is provided the value "One" needs to be changed to "FOUR"

let sampleJson = {
  Aid: 'A', detail:"sample", list: [
   {
      "Bid": "1",
      "group": [
    {
      "name": "Group A",
      "Cid": "4",
      "value": "One"
    },
    {
      "name": "Group A",
      "Cid": "41",
      "value": "1"
    },
  ]
},
{
  "Bid": "2",
  "group": [
    {
      "name": "Group A",
      "Cid": "4",
      "value": "1"
    },
    {
      "name": "Group A",
      "Cid": "4",
      "value": "1"
    },
  ]
};

I was able to access the value using below code. How can i return the entire JSON with updated value?

let variale = Immutable.fromJS(sampleJson).
getIn(['list']).
find(allocation => allocation.get("Bid") === "1").
getIn(['group']).
find(fun => fun.get("Cid") === "4").set('value',"FOUR");

Anyone has any suggestions on how to resolve this problem?

2
  • 1
    Have you looked at the setIn method? Commented Jul 28, 2016 at 4:55
  • I have looked into setIn method. setIn works when you have a ImmutableMap. It seems when I use Immutable.fromJS above json gets converted to list and map. That is where I am struggling. Commented Jul 28, 2016 at 16:39

2 Answers 2

1

I think you can try to do this like so:

let immutable = Immutable.fromJS(sampleJson);
immutable = immutable.setIn(['list', 0, 'group', 0, 'value'], 'FOUR');
Sign up to request clarification or add additional context in comments.

Comments

0

This monstrosity is how I would do it:

const newData = originalData.update('list', list => {
  const itemIndex = list.findIndex(item => item.get('Bid') === '2');

  return list.update(itemIndex, listItem => {
    return listItem.update('group', groupList => {
      const groupIndex = list.findIndex(group => group.get('Cid') === '4');

      return groupList.update(groupIndex, group => {
        return group.set('value', 'FOUR');
      });
    });
  });
});

https://jsbin.com/latupo/7/edit?html,js,console

Personally I stopped using Immutable, I always found it a bit painful (not to mention those docs!). I now use redux and good old cloning to not mutate state. Less performant in theory but if you've got nothing that runs over a few milliseconds anyway, save yourself the trouble...

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.