我有以下JSON,并希望使用Immutable.js根据Aid,Bid和Cid更新值
e.g。 提供以下输入。 Aid = A,Bid = 1,Cid = 4,NewValue =' FOUR' 如果提供了上面的输入,则值为" One"需要改为"四"
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"
},
]
};
我可以使用下面的代码访问该值。如何以更新的值返回整个JSON?
let variale = Immutable.fromJS(sampleJson).
getIn(['list']).
find(allocation => allocation.get("Bid") === "1").
getIn(['group']).
find(fun => fun.get("Cid") === "4").set('value',"FOUR");
有人对如何解决此问题有任何建议吗?
答案 0 :(得分:1)
我认为你可以尝试这样做:
let immutable = Immutable.fromJS(sampleJson);
immutable = immutable.setIn(['list', 0, 'group', 0, 'value'], 'FOUR');
答案 1 :(得分:0)
这种怪异是我如何做到的:
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
就我个人而言,我停止使用Immutable,我总觉得它有点痛苦(更不用说那些文档!)。我现在使用redux和良好的旧克隆来改变状态。理论上表现不佳,但如果你没有任何东西在几毫秒内运行,那就省去麻烦......