gpt4 book ai didi

javascript - 不可变的 : find if map contains key value

转载 作者:行者123 更新时间:2023-11-29 14:42:37 24 4
gpt4 key购买 nike

我正在尝试确定我的不可变映射的某个部分是否包含某个键值 checked: true,如果是,则在上层设置 checked: true。我正在查看的对象如下所示:

const memo = {
"Topics": {
"filters": {
"Psychological disorders": {
"filters": {
"Anxiety disorders": {
"filters": {},
"checked": true <-- check for this value at this level
}
}
}
},
"isOpen": false
}
}

注意:这个数据实际上是不可变的。

所以函数运行后会变成这样:

const memo = {
"Topics": {
"filters": {
"Psychological disorders": {
"checked": true, <-- check true added
"filters": {
"Anxiety disorders": {
"filters": {},
"checked": true
}
}
}
},
"isOpen": false
}
}

我现在唯一可以访问的变量是“主题”名称,所以我试图找出是否有任何主题 -> 过滤器 -> 过滤器在其中有 checked: true .最初,我只是想 toJS() 这个备忘录,然后用 lodash 检查里面。

像这样:

_.find(memo['Topics'], _.flow(
_.property('filters'),
_.property('filters'),
_.partialRight(_.any, { checked: true })
));

我可以使用这些信息来修改对象,但我想知道是否有可能在不将其从不可变中取出来实现这一点。到目前为止,我已经试过了:

   const nameCheck = 'Topics';

const hasCheckedFilters = memo.update(nameCheck, Map(),
(oldResult) => oldResult.update('filters', Map(),
(oldSection) => {
// filters inside this object has checked : true, .set('checked', true);
const fromImmutable = oldSection.toJS();
const checkForChecked = _.find(fromImmutable.filters, {checked:true});
if(checkForChecked) {
oldSectsion.set('checked', true);
}

}
)
)
);

这似乎不起作用,因为我没有在过滤器上循环。非常感谢任何输入,谢谢!

最佳答案

这使数据保持不变。我循环遍历 Topics.filters 中的每个属性,然后检查该属性是否具有过滤器键。如果它确实循环通过它。如果子项中的 checked 为 true,则在父项中将 checked 设置为 true 并返回一个新 map 。

const memo = {
"Topics": {
"filters": {
"Psychological disorders": {
"checked": false,
"filters": {
"Anxiety disorders": {
"filters": {},
"checked": true
}
}
}
},
"isOpen": false
}
};

let map = Immutable.fromJS(memo);

map.getIn(['Topics','filters']).forEach((item, i) => {
if(item.has('filters')){
item.get('filters').forEach(subItem => {
if(subItem.get('checked') === true){
map = map.setIn(['Topics', 'filters', i], item.set('checked', true));
}
});
}
});

console.log(JSON.stringify(map.toJS()));

http://jsbin.com/gorohewuji/edit?js,console

关于javascript - 不可变的 : find if map contains key value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36726810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com