I have a case where my JSON object needs remapping first e.g. from { name: goals, value: 65 } to { goals: 65}
. I believe I achieved that with reduce in getStats function (see screenshot from the console)
我有一个案例,我的JSON对象需要先重新映射,例如从{name:goals,value:65}到{goal:65}。我相信我通过减少getStats函数实现了这一点(参见控制台的截图)
However I want to wrap it in a function i.e. getData(name){}
where I will be passing name = 'goals'
and get the specific value 65
但是我想将它包装在一个函数中,即getData(name){},其中我将传递name ='goals'并获取特定值65
How to achieve that and simplify my code?
如何实现这一点并简化我的代码?
1 个解决方案
#1
1
Create simple getData
function which returns value for key.
创建简单的getData函数,该函数返回key的值。
getData(key, defaultValue = '') {
// I suggest to cache result of next call (invalidate cache when needed)
const data = this.getStats(playerStats);
return data[key] || defaultValue;
}
#1
1
Create simple getData
function which returns value for key.
创建简单的getData函数,该函数返回key的值。
getData(key, defaultValue = '') {
// I suggest to cache result of next call (invalidate cache when needed)
const data = this.getStats(playerStats);
return data[key] || defaultValue;
}