Javascript 在对象数组上使用过滤器/包含

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46819974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:56:54  来源:igfitidea点击:

Javascript using filter/includes on an array of objects

javascriptarrays

提问by SBB

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

过滤掉对象中存在的数据的最佳方法是什么?

I was able to do use the below code when datawas just an array of values but now I need to filterout any data where the item.QIDexists in my array of objects.

data只是一个值数组时,我能够使用下面的代码,但现在我需要filter删除item.QID对象数组中存在的任何数据。

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, includesonly works on an array so I need to treat all of the QIDvalues in my object as an array.

据我了解,includes仅适用于数组,因此我需要将QID对象中的所有值都视为数组。

Desired Outcome:(assuming item.QID = ABC123)

预期结果:(假设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. datais an object of users I want to exclude from my type-ahead results by filtering them out.

上面的代码是我正在使用的。data是我想通过过滤掉它们从我的预输入结果中排除的用户对象。

回答by CRice

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 empthat have the same QID as any item in another list data?

这个问题有点模棱两可,但我的理解(如果我错了,请纠正我),是您想从列表emp中删除与另一个列表中的任何项目具有相同 QID 的所有项目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 datahave the same QID as item.

some 是一个数组方法,如果它的回调对于任何数组元素为真,则返回真。因此,在这种情况下,some(d => d.QID === item.QID)如果列表data中的任何元素与item.

回答by Jay Hamilton

You can use a for ... in to loop through and filter out what you want:

您可以使用 for ... in 循环并过滤掉您想要的内容:

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

let newData     = [];
let filterValue = 'ABC123';

for (let value in data) {
  if (data[value].QID !== filterValue) {
    newData.push(data[value]);
  }
}

newDatawill be your new filtered array in this case

newData在这种情况下将是您的新过滤数组

回答by gavgrif

You can use an es6 .filter for that. I also added a couple of elements showing the filtered list and an input to allow changing of the filtered value. This list will update on the click of the button.

您可以为此使用 es6 .filter。我还添加了几个显示过滤列表的元素和一个允许更改过滤值的输入。此列表将在单击按钮时更新。

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

displayData(data);

function displayData(arr) {
  let str = '';
  document.getElementById('filterList').innerHTML = '';

  arr.forEach((i) => { str += "<li>" + i.QID + ": " + i.Name + "</li>"})
  document.getElementById('filterList').innerHTML = str;
}

function filterData() {
let filterValue = document.getElementById('filterInput').value;
filterText (filterValue);
}


function filterText (filterValue) {
  let newArr = data.filter((n) => n.QID !== filterValue); 
  displayData(newArr)
}
<input id="filterInput" type="text" value="ABC123" />
<button type ="button" onclick="filterData()">Filter</button>
<hr/>
<ul id="filterList"><ul>

回答by charlietfl

Try Object#hasOwnProperty()

尝试 Object#hasOwnProperty()

this.employees = emp.filter(item =>item.hasOwnProperty('QID'));