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

如何根据目标品牌数组过滤brands属性为单个字符串的对象数组

解决过滤brands为单个字符串的对象数组问题

很简单,只需要调整过滤条件里的判断逻辑就行——现在row.brands已经是单个字符串而非数组了,不需要再用some方法遍历数组元素,直接判断这个字符串是否在wantedBrands数组里就好:

let rows = [ { name: "Russia", brands: 'XM1' }, { name: "Italy", brands: 'XM5' }, { name: "Turkey", brands: 'XM5' } ];
let wantedBrands = ['XM5'];

let result = rows.filter(row => wantedBrands.includes(row.brands));
console.log(result);

运行这段代码后,你会得到预期的输出:

[ { name: "Italy", brands: 'XM5' }, { name: "Turkey", brands: 'XM5' } ]

额外:兼容brands是数组或字符串的通用写法

如果你的场景中brands可能存在格式不统一的情况(比如有时候是数组,有时候是单个字符串),可以写一个更健壮的版本,自动处理两种情况:

let result = rows.filter(row => {
  // 把单个字符串转为数组,统一处理逻辑
  const targetBrands = Array.isArray(row.brands) ? row.brands : [row.brands];
  return targetBrands.some(b => wantedBrands.includes(b));
});

内容的提问来源于stack exchange,提问作者Antanio D

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:57:36