首页 > 解决方案 > 映射一个类的数组以仅返回一组特定的属性

问题描述

我有一个类实例数组,但是我需要遍历所有这些并从类中返回一组特定的属性:

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

以上只是示例代码,它不起作用!只是想展示我正在尝试做的事情!

标签: javascript

解决方案


这是您要查找的内容,请使用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);


推荐阅读