我有如下的对象数组。
[{
"key": "remember_tip",
"description": "some remember description"
}, {
"key": "logout_tip",
"description": "some logout description"
}, {
"key": "notremember_tip",
"description": "some not remember description"
},{
"key": "backgroundOff",
"description": "some backgroundOff description"
},
{
"key": "backgroundOn",
"description": "some backgroundOn description"
},
..];
我有如下方法。
someMethod = (variable) => {
if (variable === remember) {
this.rememberHandler()
} else if (variable === logout) {
this.logoutHandler()
} else if (variable === notremember) {
this.notrememberHandler()
}else if (variable === backgroundoff) {
this.backgroundoffHandler()
}
}
rememberHandler = () => {
//showpopup with remember_tip description
}
logoutHandler = () => {
//showpopup with logout_tip description
}
notrememberHandler = () => {
//showpopup with notremember_tip description
}
backgroundoffHandler = () => {
//showpopup with backgroundOff description
}
答案 0 :(得分:1)
您可以使用当前结构来获取描述值。使用_.find()
来获取带有请求键的对象,并使用_.get()
来获取值:
const { flow, partialRight: pr, find, get } = _
const getFrom = arr => flow(
key => find(arr, { key }),
pr(get, 'description'),
)
const tips = [{
"key": "remember_tip",
"description": "some remember description"
}, {
"key": "logout_tip",
"description": "some logout description"
}, {
"key": "notremember_tip",
"description": "some not remember description"
}]
const getFromTips = getFrom(tips)
const result = getFromTips('remember_tip')
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.js"></script>
但是,对于相当简单的东西,这是很多代码。创建一个到映射的键映射。调用show
方法时,它会从Map中获取description
,并显示弹出窗口:
const tips = [{
"key": "remember_tip",
"description": "some remember description"
}, {
"key": "logout_tip",
"description": "some logout description"
}, {
"key": "notremember_tip",
"description": "some not remember description"
}, {
"key": "backgroundOff",
"description": "some backgroundOff description"
},
{
"key": "backgroundOn",
"description": "some backgroundOn description"
}
];
const tipsMap = new Map(tips.map(({ key, description }) => [key, description]))
const showpopup = console.log // demo show popup
const show = popUp => {
const description = tipsMap.get(popUp);
if (description) showpopup(description)
}
show('logout_tip')
show('backgroundOff')