0

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;
    }
}
1
  • Can you post your full data object please - even a link to an offsite resource (JSFiddle, Codepen) would be preferable to an image. Commented Dec 27, 2018 at 21:55

5 Answers 5

1

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');
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

1

Use map instead of filter.

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

Comments

1

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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.