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

在嵌套对象数组中查找目标字符串并获取对应hpid

处理声明式配置数组units的解决方案

假设你的units数组结构类似以下示例(每个元素为包含动态属性和hpid的对象):

const units = [
  {
    hpid: 'hpid-001',
    '/en/hotel-casino-chaves/rooms/': 'standard-room',
    '/pt/hotel-quarto/': 'quarto-padrao'
  },
  {
    hpid: 'hpid-002',
    '/en/restaurant-dining/': 'main-dining'
  }
];

实现两项操作的代码示例

方案1:查找第一个匹配的属性与对应hpid

如果只需要找到第一个符合条件的对象,用以下代码:

const targetStr = '/en/hotel-casino-chaves/rooms/';
let matchResult = null;

for (const unit of units) {
  // 获取当前对象的所有属性名
  const propertyNames = Object.keys(unit);
  // 筛选包含目标字符串的属性名
  const matchedProp = propertyNames.find(prop => prop.includes(targetStr));
  
  if (matchedProp) {
    matchResult = {
      matchedProperty: matchedProp,
      hpid: unit.hpid
    };
    break; // 找到第一个匹配项后终止遍历
  }
}

// 输出结果
console.log(matchResult);
// 示例输出:{ matchedProperty: '/en/hotel-casino-chaves/rooms/', hpid: 'hpid-001' }

方案2:查找所有匹配的属性与对应hpid

如果需要找出数组中所有符合条件的对象,用以下代码:

const targetStr = '/en/hotel-casino-chaves/rooms/';
const allMatches = [];

for (const unit of units) {
  const propertyNames = Object.keys(unit);
  const matchedProp = propertyNames.find(prop => prop.includes(targetStr));
  
  if (matchedProp) {
    allMatches.push({
      matchedProperty: matchedProp,
      hpid: unit.hpid
    });
  }
}

// 输出所有结果
console.log(allMatches);

注意事项

  • 若需要更精确的匹配规则(比如属性名以目标字符串开头/结尾),可以将prop.includes(targetStr)替换为prop.startsWith(targetStr)或prop.endsWith(targetStr),也可以用正则表达式(比如/^\/en\/hotel-casino-chaves\/rooms\//.test(prop))
  • 如果配置对象包含Symbol类型的属性,需要结合Object.getOwnPropertySymbols来获取完整的属性列表,替换Object.keys(unit)为[...Object.keys(unit), ...Object.getOwnPropertySymbols(unit)]

内容的提问来源于stack exchange,提问作者Leonel Matias Domingos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 01:17:03