Javascript如何过滤对象数组包含确切的单词[重复]

这个问题在这里已有答案:

如何从包含的对象中过滤数组中的“mango”一词,好吗?示例“芒果”

var myIteams= [
  {   
    title: "Title One",
    section: 1,
    tag: ["orange", "apple", "banana", "mango"]
  },
  {   
    title: "Title Two",
    section: 15,
    tag: ["mango"]
  },
  {   
    title: "Title Three",
    section: 21,
    tag: ["orange", "apple" ]
  },

]

回答(5)

2 years ago

您可以使用filterincludes来获取包含标签“Mango”的元素

过滤器:过滤器提供新数组,我们从现有数组中获取具有某些条件的元素 . 包括:它用于确定wheter数组是否包含某些元素 . 它返回true或false

var myIteams= [
  {   
    title: "Title One",
    section: 1,
    tag: ["orange", "apple", "banana", "mango"]
  },
  {   
    title: "Title Two",
    section: 15,
    tag: ["mango"]
  },
  {   
    title: "Title Three",
    section: 21,
    tag: ["orange", "apple" ]
  },

];

var result = myIteams.filter(x => x.tag.includes("mango"));
console.log(result);

2 years ago

您可以使用Array.filter . 它需要一个函数,它应返回'truthy'或'falsey' . 如果它返回一些真实的东西,它会保留该项目,否则它会被过滤掉 .

var myIteams= [
  {   
    title: "Title One",
    section: 1,
    tag: ["orange", "apple", "banana", "mango"]
  },
  {   
    title: "Title Two",
    section: 15,
    tag: ["mango"]
  },
  {   
    title: "Title Three",
    section: 21,
    tag: ["orange", "apple" ]
  },

]

const result = myIteams.filter(item => item.tag.indexOf('mango') > -1)

console.dir(result)

2 years ago

只需使用 Array.prototype.filter 通过回调过滤数组 . 然后使用 Array.prototype.includes 匹配正确的项目 .

var myItems = [
  {   
    title: "Title One",
    section: 1,
    tag: ["orange", "apple", "banana", "mango"]
  },
  {   
    title: "Title Two",
    section: 15,
    tag: ["mango"]
  },
  {   
    title: "Title Three",
    section: 21,
    tag: ["orange", "apple" ]
  },

];

const match = myItems.filter(item => {
  return item.tag.includes('mango');
});
console.log(match);

2 years ago

您可以使用 filter 过滤数组,使用 some 查找包含所需值的标记列表 .

var myItems = [{
    title: "Title One",
    section: 1,
    tag: ["orange", "apple", "banana", "mango"]
  },
  {
    title: "Title Two",
    section: 15,
    tag: ["mango"]
  },
  {
    title: "Title Three",
    section: 21,
    tag: ["orange", "apple"]
  },

]


const filtered = myItems.filter(o => o.tag.some(t => t === 'mango'));
console.log(filtered);

2 years ago

您可以在其中使用包含方法的filter方法 . 以下是创建一个函数的示例,该函数允许您传入要查找的项目 .

var myItems = [
  {   
    title: "Title One",
    section: 1,
    tag: ["orange", "apple", "banana", "mango"]
  },
  {   
    title: "Title Two",
    section: 15,
    tag: ["mango"]
  },
  {   
    title: "Title Three",
    section: 21,
    tag: ["orange", "apple" ]
  },
];

function findItem(itemToFind) {
  return myItems.filter(item => item.tag.includes(itemToFind));
}

console.log(findItem('mango'))