我已经成功地过滤了我的数组,因此显示的唯一对象是在 Course 中包含字符串“东部”的对象。
// Empty array + object that is pushed onto array following Btn click
var dataSet = [];
dataObj = {Course: courseSelect.value, Score: scoreText.value, Pars: parsText.value, Birdies: birdiesText.value};
dataSet.push(dataObj);
// Filter
findVal = dataSet.filter(findVal => findVal.Course === 'eastern');
现在唯一的问题是,如果我只想使用 console.log(findVal.Score)
从该对象中分离出 Score 值,它会返回 undefined。我希望它从过滤后的数组中的每个对象返回每个 Score 值,但它没有。
我该如何克服这个问题?
最佳答案
因为 findVal
它是一个数组,你应该使用 map
方法结合 destructuring 方法来获得 Score
数组中每个项目的属性。
findVal = dataSet
.filter(findVal => findVal.Course === 'eastern')
.map(({Score}) => Score);
关于javascript - 使用Array.filter后如何获取多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55937830/