user14241810
user14241810

Reputation:

How to filter an array from an object

i have a check box that i populate as follows

<div repeat.for="list of Items" change.delegate="getClicked()"  >

<md-checkbox  checked.bind="List" model.bind="list" >${list.name}</md-checkbox>
</div>

i have another list in my ts page that returns all the items and is stored as follows

getClicked()
{
let result= this.ItemList  // this object contains a list of items
}

what i wanted to achieve is if i click on the checkbox i want to get the id and filter it on the ItemList object to only return that items.

This is what i have

getClicked() {
        
        let Id = this.List.map(x=> x.id);
        let result = this.ItemList.filter(x => x.ItemId === Id)
}

Items=[{ id: 11125e, name:"coke" },
        { id: 11125e,name:"juice" },
        { id: 33e4,name:"chips" }]

the problem i am having is that my result is always returned as [] empty.

this is what is happening when i get the id for example

let Id = this.List.map(x=> x.id);// id returned["11125e"]
            let result = this.ItemList.filter(x => x.ItemId ===["11125e"] ) // id gets passed with [] around it

but if i have to manualy test and i do this with out the [] it works and i get a result back

let result = this.ItemList.filter(x => x.ItemId ==="11125e" )

so my question is how do i get this.List.map(x=> x.id);// id returned["11125e"] to be "11125e"

Upvotes: 0

Views: 32

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37918

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array

What you're looking for is find

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.


let result = this.ItemList.find(x => x.ItemId ==="11125e")

Upvotes: 1

Related Questions