Skip to content
Advertisement

Create object from another one using filter function

I’m trying to create an array of objects using an array of objects. My first array is like that : enter image description here

And I want to create an object list with only an id, a name and a task. This is what i do actually, but it doesn’t work :

var lists = data.filter(l => {
            return new ListModel(l.listId, l.listName, 'todo');
});

The ListModel object is :

class ListModel {
    constructor(id, name, tasks) {
        this.id = id;
        this.name = name;
        this.tasks = tasks;
    }

    setId(id) {
        this.id = id;
    }

    setName(name) {
        this.name = name;
    }

    setTask(task) {
        this.task = task;
    }
}

Advertisement

Answer

The filter() function is more-so utilized for returning an array based upon some search criteria, similar to a WHERE clause. What you want is to utilize is the map() function using something like this:

var lists = data.map(l => {
    return new ListModel(l.listId, l.listName, 'todo');
});
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement