Clément Drouin
Clément Drouin

Reputation: 395

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

Upvotes: 0

Views: 1508

Answers (5)

Jack Bashford
Jack Bashford

Reputation: 44125

You're currently using Array.prototype.filter(), which removes non-matching elements from the current array. What you want to do, as far as I can tell, is use Array.prototype.map() to create a new array based upon the ListModel object. Here's how you'd do it:

var lists = data.map(l => new ListModel(l.listId, l.listName, "todo"));

Upvotes: 1

varoons
varoons

Reputation: 3887

Use map instead of filter.

Filter creates a new array with all elements that pass the test implemented by the provided function/expression.

Upvotes: 1

Joel Brewer
Joel Brewer

Reputation: 1652

I think you want the map() function: https://www.w3schools.com/jsref/jsref_map.asp

Something like this:

const newData = data.map( item => {
  return {
    item.listId,
    item.listName,
    'todo',
  }
})

Upvotes: 1

Ben
Ben

Reputation: 2706

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');
});

Upvotes: 1

Nelson Teixeira
Nelson Teixeira

Reputation: 6572

Use .map instead of .filter:

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

filter is for filtering elements, and the return value is taken as a boolean value for this. So in your case all elements will be validated because a new object is allways a truthy value, and you'll get a equal array.

Edit your question with the original array in text format and I'll create a working example for you.

Upvotes: 1

Related Questions