[英]Object keys to string based on value
Good evening,晚上好,
Within React state I have the following object: ... .modals{search: true, social: false, menu: true, login: false}
在 React state 我有以下 object:
... .modals{search: true, social: false, menu: true, login: false}
The Boolean values change depending on whether certain modals are active. Boolean 值会根据某些模态是否处于活动状态而变化。 I would like to extract the active modals based on
true
and return them into a data-modal
property within my react component - so that I can use them for conditional CSS.我想基于
true
提取活动模态并将它们返回到我的反应组件中的data-modal
属性中 - 这样我就可以将它们用于有条件的 CSS。
As an example the result of above would be data-modal="search menu"
.例如,上面的结果是
data-modal="search menu"
。 In other words, those keys that have a positive value are added to the string.换句话说,那些具有正值的键被添加到字符串中。
I've played around with a few things;我玩过一些东西; join, map, foreach etc, but can't find a combination that works.
加入,map,foreach 等,但找不到有效的组合。
Any help would be appreciated.任何帮助,将不胜感激。
const properties = {search: true, social: false, menu: true, login: false}; const whatYouNeed = Object.keys(properties).reduce((acc,val) =>acc + (properties[val]? `${val} `: ''),'').trim(); console.log(whatYouNeed);
const modals = {search: true, social: true, menu: true, login: false}
let active = ''
for(key in modals) {
if(modals[key]) active += ' ' + key;
}
Now you can pass to data-modal={active}
现在您可以传递给
data-modal={active}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.