如何从React中的JSON对象中提取值?

时间:2022-12-10 16:00:49

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?

如何实现这一点并简化我的代码?

如何从React中的JSON对象中提取值?

如何从React中的JSON对象中提取值?

如何从React中的JSON对象中提取值?

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;
}