用另一个数组的数组属性过滤对象数组

时间:2019-03-05 15:38:41

标签: javascript arrays filter

以下代码不返回包含1个项目的数组的预期结果。有人可以启发我正确的语法吗?

let things = [{
    Name: 'Bill',
    Tags: ['tall', 'dude']
  },
  {
    Name: 'Ted',
    Tags: ['short', 'dude']
  }
];

let selectedTags = ['short', 'chick'];

let filtered = things.filter((thing => thing.Tags.indexOf(selectedTags) >= 0));
console.log(filtered);

5 个答案:

答案 0 :(得分:0)

您正在将数组selectedTags传递给includes。您需要检查通过selectedTags的循环,并检查对象的.Tags中是否存在标签。

let things = [{Name: 'Bill', Tags: ['tall','dude']},
              {Name: 'Ted', Tags: ['short','dude']}];
console.log(things);

let selectedTags = ['short','chick'];

let filtered = things.filter(x => {
  for(let tag of selectedTags){
    if(x.Tags.includes(tag)) return true;
  }
  return false;
});
console.log(filtered);

答案 1 :(得分:0)

selectedTags是一个数组。

.indexOf()正在等待字符串。

您可以通过使用索引选择将字符串放入数组中,例如:

thing.Tags.indexOf(selectedTags[0])

答案 2 :(得分:0)

因此,您似乎想根据things中是否有thing.Tags来过滤selectedTags

您会做这样的事情

things.filter(thing => thing.Tags.some(tag => selectedTags.includes(tag)));

我认为这是最有表现力的书写方式。把所有东西都给我,标记在selectedTags数组中。

答案 3 :(得分:0)

如果您需要过滤tag数组中包含selectedTags的项目,则可以执行以下操作:

let things = [
  {Name: 'Bill', Tags: ['tall', 'dude']},
  {Name: 'Ted', Tags: ['short', 'dude']}
];

let selectedTags = ['short', 'chick'];

let filtered = things.filter(
    thing => selectedTags.some(x => thing.Tags.includes(x))
);
    
console.log(filtered);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

如果您需要过滤在tags数组中包含所有selectedTags的项目,则可以使用:

let things = [
  {Name: 'Bill', Tags: ['tall', 'dude']},
  {Name: 'Ted', Tags: ['short', 'dude']},
  {Name: 'Test', Tags: ['short', 'chick']}
];

let selectedTags = ['short', 'chick'];

let filtered = things.filter(
    thing => selectedTags.every(x => thing.Tags.includes(x))
);
    
console.log(filtered);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

答案 4 :(得分:0)

您必须遍历每个things元素并分析其Tags属性数组中的每个项目:

let things = [{
    Name: 'Bill',
    Tags: ['tall', 'dude']
  },
  {
    Name: 'Ted',
    Tags: ['short', 'dude']
  }
];

let selectedTags = ['short', 'chick'];
let filtered = things.filter(el => {
  //Use reduce on to get a count of how many matching tags
  return el.Tags.reduce((accum, tag) => {
    if (selectedTags.indexOf(tag) > -1) {
      accum += 1;
    }
    return accum;
  }, 0);
});

console.log(filtered);