可以说我有以下数据:
# A tibble: 9 x 10
# Groups: Date, Category [9]
Category Date Beta1 Beta2 Column1 Column2 Col1Bet1 Col1Bet2 Col2Bet1 Col2Bet2
<fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A 2001 1 2 10 40 10 20 40 80
2 A 2002 3 4 20 50 60 80 150 200
3 A 2003 4 6 30 60 120 180 240 360
4 B 2001 4 1 10 40 40 10 160 40
5 B 2002 5 1 20 50 100 20 250 50
6 B 2003 3 2 30 60 90 60 180 120
7 C 2001 5 5 10 40 50 50 200 200
8 C 2002 3 4 20 50 60 80 150 200
9 C 2003 1 2 30 60 30 60 60 120
我已经进行了API调用,以将这些数据输入到我的React应用程序中:
stockData: [
{
"ticker": "AAPL",
"name": "Apple Inc",
"priceChanges": {
"daily": 0.0155,
"weekly": -0.0355,
"monthly": -0.2000
},
"financialData": {
"roa": 0.0574,
"roe": 0.2007,
"market_cap": "1.2T"
}
},
{
"ticker": "MSFT",
"name": "Microsoft Corporation",
"priceChanges": {
"daily": 0.0435,
"weekly": 0.0125,
"monthly": -0.2205
},
"financialData": {
"roa": 0.0873,
"roe": 0.1507,
"market_cap": "1.3T"
}
}
]
现在我的问题是我必须将所有这些NUMERIC属性值(stockData.priceChanges.daily,stockData.financialData.roa等)转换为百分比,这意味着我必须将它们乘以100,以便以后可以显示它们正确地在表中使用修改后的数组以实现不同的功能。 由于我必须修改的数组中的属性是嵌套的,因此我不确定如何解决此问题。
如果未嵌套这些值,我将尝试这样处理:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
stockData: [],
}
}
componentDidMount() {
axios.get("http://localhost:8080/stocks")
.then(response => {
this.setState({
stockData: response.data
})
})
}
}
答案 0 :(得分:1)
您可以更新将要在表格或某些组件中显示的值,但是如果您要更新数据以使百分比百分比值保持不变,则只需使用forEach或map()即可更新数据
假设您从api中获取了此数据
const data = [
{
"ticker": "AAPL",
"name": "Apple Inc",
"priceChanges": {
"daily": 0.0155,
"weekly": -0.0355,
"monthly": -0.2000
},
"financialData": {
"roa": 0.0574,
"roe": 0.2007
}
},
{
"ticker": "MSFT",
"name": "Microsoft Corporation",
"priceChanges": {
"daily": 0.0435,
"weekly": 0.0125,
"monthly": -0.2205
},
"financialData": {
"roa": 0.0873,
"roe": 0.1507
}
}
];
const stock = data.map(d => {
const priceChanges = {
"daily": d.priceChanges.daily * 100,
"weekly": d.priceChanges.weekly * 100,
"monthly": d.priceChanges.monthly * 100
};
const financialData = {
"roa": d.financialData.roa * 100,
"roe": d.financialData.roa * 100
};
return {
...d,
priceChanges,
financialData
}
});
console.log(stock);
答案 1 :(得分:0)
如果每个嵌套对象都将转换为百分比,请使用以下方法:
a.map(obj => {
Object.keys(obj).forEach(key => {
if(typeof obj[key] === "object") {
Object.keys(obj[key]).forEach(_key => {
obj[key][_key] = obj[key][_key] * 100
});
}
});
return obj
});