javascript - 映射一个类的数组以仅返回一组特定的属性
问题描述
我有一个类实例数组,但是我需要遍历所有这些并从类中返回一组特定的属性:
class Checkbox {
constructor() {
this.test1 = 'dsdas';
this.test2 = 'dsdas';
this.test3 = 'dsdas';
this.test4 = 'dsdas';
}
onlySome() {
return {
test3: this.test3 || null,
test4: this.test4 || null,
}
}
}
const fields = {
class1: Checkbox,
class2: Checkbox,
class3: Checkbox,
class4: Checkbox,
}
const filtered = fields.map(value => value.onlySome());
地图不起作用,最好的方法是什么,代码应该对我想要做什么有意义?
所以filtered
会是这样的:
const filtered = {
class1: <Checkbox>{
test3: dsdas,
test4: dsdas,
}
}
以上只是示例代码,它不起作用!只是想展示我正在尝试做的事情!
解决方案
这是您要查找的内容,请使用Object.keys
然后使用,map
因为它是一个对象。
class Checkbox {
constructor() {
this.test1 = 'dsdas';
this.test2 = 'dsdas';
this.test3 = 'dsdas';
this.test4 = 'dsdas';
}
onlySome() {
return {
test3: this.test3 || null,
test4: this.test4 || null,
}
}
}
const fields = {
class1: new Checkbox(), //instantiate it first
class2: new Checkbox(), //instantiate it first
class3: new Checkbox(), //instantiate it first
class4: new Checkbox(), //instantiate it first
}
const filtered = Object.keys(fields).map(key => {
return {
[key]: fields[key].onlySome()
}
});
console.log(filtered);
推荐阅读
- json - JSON 中的转义 HTML 字符串无效
- python - Can I retrain OpenCV DNN face detector using my own face dataset and .pb .pbtxt files provided by OpenCV?
- javascript - 尝试在我的 React 项目中设置状态时无法读取未定义的属性 setState
- java - RxJava:将 Observable 与 Completable 合并不起作用
- python - 如何使用python获取日期后的文本?
- reactjs - 文件的 onMouseDown 函数
- jquery - jquery sortable 在排序前删除下一行
- angular - Angular 7 AmCharts PDF 字体
- python - 尝试使用 ' 'join(x.split()) 删除一些重复的空格但失败
- c# - 如何在 .ASP.NET Core MVC 中使用多个登录页面以及未经授权的用户重定向不同的登录页面