javascript - 将 Javascript Map 函数返回的数组保存到新数组
问题描述
我有一个对象数组。我想要一个包含相同元素但仅包含其x
属性的新数组。
所以原始数组是:
[{x: "401K", y:1000}, {x: "RSU": y: 6000}]
新数组将是:
["401k", "RSU"]
我努力了:
const legend = this.state.pieChartData.map(a => a.x)
当我传入this.state.pieChartData.map(a => a.x))
的console.log
回调函数时setstate
,它会打印正确的数组。但是当 I console.log(this.state.pieLegend)
() 它是一个空数组。
computeTotals(){
var runningTotal = 0
var pieArray = []
var beyondBudget = {}
const legend = this.state.pieChartData.map(a => a.x)
console.log("this does not show correct array", legend)
//filter out all $0 answers
Object.keys(this.state.data.selectedQuestions)
.filter(key => Object.values(this.state.data.selectedQuestions[key])[0] != 0)
.map((key, index) => {
const value = Object.values(this.state.data.selectedQuestions[key])[0]
const name = key
runningTotal += value
//still not gone beyond budget, add to pie chart
if(runningTotal <= 1600){
let pieSlice =
{
x: name,
y: value
};
pieArray = pieArray.concat(pieSlice)
}
//went beyond budget, add to beyondbudget table data
else {
if (Object.keys(beyondBudget).length == 0) {
beyondBudget[name] = {};
beyondBudget[name] = runningTotal - 1600;
let pieSlice =
{
x: name,
y: value - (beyondBudget[name])
};
pieArray = pieArray.concat(pieSlice)
}
if (!beyondBudget[name]) {
beyondBudget[name] = {};
}
if (Object.keys(beyondBudget).length > 1) {
beyondBudget[name] = value;
}
}
})
this.setState({
pieChartData: pieArray,
total: runningTotal,
beyondBudget: beyondBudget,
pieLegend: this.state.pieChartData.map(a => a.x)
}, () => {
console.log("this shows correct array", this.state.pieChartData.map(a => a.x));
console.log("this does not", this.state.pieLegend)
this.computePiePercentages();
});
}
我认为问题是我没有返回任何东西。所以我尝试了这个:
const legend = this.state.pieChartData.map(function justName(item){
console.log("test!")
return item.x
}
但是我的测试语句没有打印事件。
解决方案
如图所示,您的setState
方法将无法正常工作:
this.setState({
pieChartData: pieArray,
total: runningTotal,
beyondBudget: beyondBudget,
pieLegend: this.state.pieChartData.map(a => a.x)
}, () => {});
您在设置pieLegend
的this.state.pieChartData.map(a => a.x)
同时设置为pieChartData
. 但是因为它同时(并且可能在Object.assign()
内部进行),所以 pieChartData 的值在this.state.pieChartData.map(a => a.x)
评估时仍然是未定义的,因此 state.pieLegend 也将是未定义的。
在尝试映射它之前,您需要先设置 pieChartData,或者只映射 pieArray 以开始:
this.setState({
pieChartData: pieArray,
total: runningTotal,
beyondBudget: beyondBudget,
pieLegend: pieArray.map(a => a.x)
}, () => {});
推荐阅读
- javascript - 如何从 javascript 函数内部调用 jquery buttonclick 函数
- ant - 带有空输入字符串的 apache Ant 基本名称问题
- asp.net-mvc - Azure 应用服务上的瞬态无限登录循环 - 使用 Azure AD 进行 OpenIDConnect 身份验证
- php - 如何从字符串中添加数字
- html - Bootstrap 4 - Ubuntu Chrome 和 Firefox 中不同的渲染字体大小
- python - 使用opencv和python从具有可变帧速率的IP摄像机录制视频
- android - 如何使用 Mockito 的 doAnswer 测试 void 方法
- selenium - 并行测试的范围报告 - Xunit 和 specflow
- django - WSGIPythonPath 上的 LOST 采用一个参数,Python 模块搜索路径
- ruby-on-rails - ruby on rails 中自定义日志文件的日志轮换