javascript 使用filter数组过滤对象数组[duplicate]

f0brbegy  于 2023-01-04  发布在  Java
关注(0)|答案(4)|浏览(225)
    • 此问题在此处已有答案**:

Filter array of objects based on another array in javascript(10个答案)
昨天关门了。
我正在尝试使用2个条件筛选数组:一个是straigthforward(== 1),另一个是数组。在下面的例子中,我想过滤:级别= 0名称包含在['B','S']

[
{id: 1, level: 0, name: 'A'},
{id: 2, level: 1, name: 'B'},
{id: 3, level: 1, name: 'S'},
{id: 4, level: 0, name: 'A'},
{id: 5, level: 0, name: 'S'},
{id: 6, level: 1, name: 'A'},
{id: 7, level: 0, name: 'B'}, ]

所以结果是:

[
{id: 1, level: 0, name: 'A'},
{id: 2, level: 1, name: 'B'},
{id: 3, level: 1, name: 'S'},
{id: 4, level: 0, name: 'A'},
{id: 5, level: 0, name: 'S'},
{id: 7, level: 0, name: 'B'}, ]

由于我受ecmaScript-5的限制,我不能使用。包括这将有助于这里。
另外,我想坚持使用. filter函数。
你知道怎么做吗?
谢谢

bqujaahr

bqujaahr1#

使用ecmaScript-5可以执行以下操作:

var arr = [{ id: 1, level: 0, name: 'A' },{ id: 2, level: 1, name: 'B' },{ id: 3, level: 1, name: 'S' },{ id: 4, level: 0, name: 'A' },{ id: 5, level: 0, name: 'S' },{ id: 6, level: 1, name: 'A' },{ id: 7, level: 0, name: 'B' },]

var result = arr.filter(function (obj) {
  return obj.level === 1 || ['B', 'S'].indexOf(obj.name) > -1;
})

console.log(result)
wfsdck30

wfsdck302#

一个简单的循环就可以实现这一点-并将匹配的项推入一个新的数组中,该数组将包含所需的项。

我已经避免了使用更新的、更令人兴奋的方法来实现旧的var和forEach方法,以满足您的ecma-5要求。

var arr = [
{id: 1, level: 0, name: 'A'},
{id: 2, level: 1, name: 'B'},
{id: 3, level: 1, name: 'S'},
{id: 4, level: 0, name: 'A'},
{id: 5, level: 0, name: 'S'},
{id: 6, level: 1, name: 'A'},
{id: 7, level: 0, name: 'B'}, ]

var newArr = [];

arr.forEach(function(item) {
  if(item.level === 1 || (item.name === 'A' || item.name ==='B')) {
   newArr.push(item)
  }
})

console.log(newArr);

//gives[
  //{id: 1,level: 0, name": "A"},
  //{id: 2, level: 1, name: "B"},
  //{id: 3, level: 1, name: "S"},
  //{id: 4, level: 0, name: "A"},
  //{id: 6, level: 1, name: "A"},
  //{id: 7, level: 0, name: "B"}]
cgvd09ve

cgvd09ve3#

const arr = [
  { id: 1, level: 0, name: 'A' },
  { id: 2, level: 1, name: 'B' },
  { id: 3, level: 1, name: 'S' },
  { id: 4, level: 0, name: 'A' },
  { id: 5, level: 0, name: 'S' },
  { id: 6, level: 1, name: 'A' },
  { id: 7, level: 0, name: 'B' },
];

const newArr = arr.filter(
  item => item.level === 0 || item.name === 'B' || item.name === 'S'
);

console.log(newArr);
kq4fsx7k

kq4fsx7k4#

可以将Array.prototype.filter()方法与Array.prototype.indexOf()方法沿着使用,以根据条件筛选数组:

const array = [
  {id: 1, level: 0, name: 'A'},
  {id: 2, level: 1, name: 'B'},
  {id: 3, level: 1, name: 'S'},
  {id: 4, level: 0, name: 'A'},
  {id: 5, level: 0, name: 'S'},
  {id: 6, level: 1, name: 'A'},
  {id: 7, level: 0, name: 'B'},
];

var names = ['B', 'S'];

var result = array.filter(item => item.level === 0 || names.indexOf(item.name) !== -1);

console.log(result)

相关问题