Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript using filter/includes on an array of objects

What is the best way to filter out data that exists within an object?

I was able to do use the below code when data was just an array of values but now I need to filter out any data where the item.QID exists in my array of objects.

Data Obj:

var data = [{
  QID: 'ABC123',
  Name: 'Joe'
},
{
 QID: 'DEF456',
 Name: 'Bob
}]

Snippet:

// I don't want to include data if this QID is in my object
this.employees = emp.filter(item =>!this.data.includes(item.QID));

From what I understand, includes only works on an array so I need to treat all of the QID values in my object as an array.

Desired Outcome: (assuming item.QID = ABC123)

this.employees = emp.filter(item =>!this.data.includes('ABC123'));

Result:

var data = [{
  QID: 'DEF456',
  Name: 'Bob'
}]

UPDATE: Apologies, I left some things a little unclear trying to only include the necessary stuff.

// People Search
    this.peopleSearchSub = this.typeahead
        .distinctUntilChanged()
        .debounceTime(200)
        .switchMap(term => this._mapsService.loadEmployees(term))
        .subscribe(emp => {
            // Exclude all of the current owners
            this.employees = emp.filter((item) => item.QID !== this.data.QID);
        }, (err) => {
            this.employees = [];
        });

The above code is what I am working with. data is an object of users I want to exclude from my type-ahead results by filtering them out.

like image 321
SBB Avatar asked Oct 18 '17 22:10

SBB


People also ask

Can you use filter on an array of objects JavaScript?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


1 Answers

The question is a little ambiguous, but my understanding (correct me if I'm wrong), is that you want to remove all items from a list emp that have the same QID as any item in another list data?

If that's the case, try:

this.employees = emp.filter(item => !this.data.some(d => d.QID === item.QID))

some is an array method that returns true if it's callback is true for any of the arrays elements. So in this case, some(d => d.QID === item.QID) would be true if ANY of the elements of the list data have the same QID as item.

like image 187
CRice Avatar answered Sep 28 '22 05:09

CRice