映射中的返回Object.keys未定义 [英] return Object.keys in a map got undefined

查看:109
本文介绍了映射中的返回Object.keys未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的循环有什么问题?我想计算total_count并在映射中进行一些操作后返回[total,total],但是我不确定.

What's wrong with my loop below? I want to calculate the total_count and return [total, total] after some manipulation within a map, but I got undefined.

我的raw数据

const raw = [{
  "device_info": {
    "name": "cam1",
  },
  "age_range": {
    "0-10": {
      "age_range": "0-10",
      "total_count": 15,
      "male_count": 6,
      "female_count": 9
    },
    "11-20": {
      "age_range": "11-20",
      "total_count": 11,
      "male_count": 7,
      "female_count": 4
    },
    "21-30": {
      "age_range": "21-30",
      "total_count": 922,
      "male_count": 452,
      "female_count": 470
    }
  }
}, {
  "device_info": {
    "name": "cam2",
  },
  "age_range": {
    "0-10": {
      "age_range": "0-10",
      "total_count": 1,
      "male_count": 1,
      "female_count": 0
    },
    "11-20": {
      "age_range": "11-20",
      "total_count": 2,
      "male_count": 0,
      "female_count": 2
    },
    "21-30": {
      "age_range": "21-30",
      "total_count": 90,
      "male_count": 58,
      "female_count": 32
    }
  }
}]

循环

const x = raw.map(obj => {
  return Object.keys(obj).forEach(key => {
    let total = 0
    if (key === 'age_range') {
      total = Object.keys(obj.age_range).reduce((acum, innerKey) => {
        return acum + obj.age_range[innerKey].total_count
      }, 0)
      console.log(total)
    }
  });
})

console.log('x', x)

https://jsfiddle.net/19m3f7fs/1

推荐答案

Array#forEach不返回任何内容,请使用

Array#forEach doesn't return anything, use Array#map and Object.values instead:

const x = raw.map(obj => {
  return Object.values(obj.age_range).reduce((acc, item) => acc + item.total_count, 0)
})

工作示例:

const raw = [{
  "device_info": {
    "name": "cam1",
  },
  "age_range": {
    "0-10": {
      "age_range": "0-10",
      "total_count": 15,
      "male_count": 6,
      "female_count": 9
    },
    "11-20": {
      "age_range": "11-20",
      "total_count": 11,
      "male_count": 7,
      "female_count": 4
    },
    "21-30": {
      "age_range": "21-30",
      "total_count": 922,
      "male_count": 452,
      "female_count": 470
    }
  }
}, {
  "device_info": {
    "name": "cam2",
  },
  "age_range": {
    "0-10": {
      "age_range": "0-10",
      "total_count": 1,
      "male_count": 1,
      "female_count": 0
    },
    "11-20": {
      "age_range": "11-20",
      "total_count": 2,
      "male_count": 0,
      "female_count": 2
    },
    "21-30": {
      "age_range": "21-30",
      "total_count": 90,
      "male_count": 58,
      "female_count": 32
    }
  }
}]

const x = raw.map(obj => Object.values(obj.age_range).reduce((acc, item) => acc + item.total_count, 0))

console.log(x)

这篇关于映射中的返回Object.keys未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆