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

如何匹配JavaScript数组对象与目标对象并累加low、high属性值?

问题:累加匹配的JavaScript对象属性值

原始数据

const obj = [
  { 'name': 'skip', low: 20, high: 10 },
  { 'name': 'jump', low: 5, high: 20},
  { 'name': 'tall', low: 3, high: 2},
  { 'name': 'wind', low: 5, high: 10},
  { 'name': 'hire', low: 7, high: 6 }
]

const finalObj = {
  'Shopping mall': {
    'names': ['skip', 'jump'],
    'low': 0,
    'high': 0
  },
  'Parking garage': {
    'names': ['hire'],
    'low': 0,
    'high': 0
  },
  'Falling Tower': {
    'names': ['tall', 'wind'],
    'low': 0, 
    'high': 0
  }
}

需求说明

当obj中对象的name属性匹配finalObj各子对象的names数组元素时,将对应obj对象的low和high值累加到finalObj对应子对象的low、high属性中,期望输出如下:

const finalObj = {
  'Shopping mall': {
    'names': ['skip', 'jump'],
    'low': 25,
    'high': 30
  },
  'Parking garage': {
    'names': ['hire'],
    'low': 7,
    'high': 6
  },
  'Falling Tower': {
    'names': ['tall', 'wind'],
    'low': 8, 
    'high': 12
  }
}

错误尝试代码

for (const o in obj) {
 for (const f in Object.entries(finalObj)) {
   if (f[1]['names'].indexOf(obj[o].name >= 0)) {
     console.log("matched name : " + obj[o].name)
   }
 }
}

问题分析

你的代码存在几个关键错误:

  1. 遍历数组用for...in不合适:for...in遍历数组时得到的是索引值,而非数组元素,应该用for...of或者数组方法。
  2. 遍历Object.entries结果的方式错误:Object.entries(finalObj)返回键值对数组,用for...in遍历得到的是数组索引,不是键值对元素,同样需要用for...of。
  3. 条件判断括号位置错误:obj[o].name >=0是把字符串name和数字0比较,逻辑完全错误,正确的写法应该是f[1]['names'].indexOf(obj[o].name) >= 0,更推荐用includes方法判断存在性。

正确解决方案

方案一:嵌套循环直接匹配

// 遍历finalObj的每个分类
for (const [category, categoryData] of Object.entries(finalObj)) {
  // 遍历当前分类下的所有name
  for (const name of categoryData.names) {
    // 在obj中找到对应name的对象
    const matchedItem = obj.find(item => item.name === name);
    if (matchedItem) {
      categoryData.low += matchedItem.low;
      categoryData.high += matchedItem.high;
    }
  }
}

方案二:构建映射提升效率(适合大数据量)

先把obj转换成以name为键的映射对象,后续查找可以直接通过键获取,避免重复遍历数组:

// 构建name到对象的映射
const nameToItemMap = obj.reduce((map, item) => {
  map[item.name] = item;
  return map;
}, {});

// 遍历finalObj的所有分类数据
for (const categoryData of Object.values(finalObj)) {
  for (const name of categoryData.names) {
    const item = nameToItemMap[name];
    if (item) {
      categoryData.low += item.low;
      categoryData.high += item.high;
    }
  }
}

两种方案执行后,finalObj都会得到期望的结果,方案二在obj数据量较大时性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:32:06