You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何返回数组中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 the fruits array, and returns a brand new array with only the objects that meet our condition.
  • fruit.name.includes('apples') checks if the name string 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:27:09