如何返回数组中name属性字符串包含指定值的对象?
How to filter objects where name contains 'apples' from an array
Hey there! Let's break down how to pull out the objects where the name property includes the substring 'apples' from your fruits array.
The easiest way to do this in JavaScript is using the filter() method paired with includes() for string checking. Here's a working, ready-to-use example:
const fruits = [ { name: 'apples, lemon', quantity: 2 }, { name: 'bananas, pearl', quantity: 0 }, { name: 'cherries, pineapple', quantity: 5 } ]; // Filter the array to keep only objects with 'apples' in the name const applesContainingFruits = fruits.filter(fruit => fruit.name.includes('apples')); console.log(applesContainingFruits); // Output: [{ name: 'apples, lemon', quantity: 2 }]
A quick breakdown of how this works:
filter()loops through every object in thefruitsarray, and returns a brand new array with only the objects that meet our condition.fruit.name.includes('apples')checks if thenamestring of each fruit object contains the exact substring 'apples' — note that this is case-sensitive by default.
Want case-insensitive matching?
If you need to catch variations like 'Apples' or 'APPLES' too, just convert both the name and search term to lowercase:
const applesFruitsCaseInsensitive = fruits.filter(fruit => fruit.name.toLowerCase().includes('apples'.toLowerCase()) );
This way, any case variation of 'apples' in the name will trigger a match.
内容的提问来源于stack exchange,提问作者Paweł Doliński
相关产品推荐
相关产品推荐

