访问带有变量的嵌套Javascript对象

Accessing nested Javascript object with variables

本文关键字:嵌套 Javascript 对象 变量 访问      更新时间:2023-09-26

我试图找到每个通道的总和,以获得energy_ac的总能量。这就是映射。

var mappings = [
{
  floor: 13,
  name: 1301,
  room_type: 'room',
  energy_ac: [
    {deviceId: 15062, channels: ['ct1']},
    {deviceId: 15063, channels: ['ct1', 'ct2', 'ct3']}
  ],
  energy_light: [
    {deviceId: 15062, channels: ['ct4']}
  ],
  energy_socket1: [
    {deviceId: 15062, channels: ['ct5']}
  ],
  energy_socket2: [
    {deviceId: 15062, channels: ['ct5']}
  ]
}  ];

这是数据:

data = { '15062':
   { _id: 550fea1b46758f1505dd70c7,
 deviceId: '15062',
 link: 'http://egauge15062.egaug.es/cgi-bin/egauge-show?S&s=0&n=6&C&Z=LST-8',
 timestamp: 1427106327,
 ct1: 34,
 ct2: 0,
 ct3: 7,
 ct4: 572,
 ct5: 527 },
  '15063':
   { _id: 550fea1b46758f1505dd70c8,
 deviceId: '15063',
 link: 'http://egauge15062.egaug.es/cgi-bin/egauge-show?S&s=0&n=6&C&Z=LST-8',
 timestamp: 1427106327,
 ct1: 34,
 ct2: 0,
 ct3: 7,
 ct4: 572,
 ct5: 527 },
  '15064':
{ _id: 550fea1b46758f1505dd70c9,
 deviceId: '15064',
 link: 'http://egauge15062.egaug.es/cgi-bin/egauge-show?S&s=0&n=6&C&Z=LST-8',
 timestamp: 1427106327,
 ct1: 34,
 ct2: 0,
 ct3: 7,
 ct4: 572,
 ct5: 527 },
  '15065':
   { _id: 550fea1b46758f1505dd70ca,
 deviceId: '15065',
 link: 'http://egauge15062.egaug.es/cgi-bin/egauge-show?S&s=0&n=6&C&Z=LST-8',
 timestamp: 1427106327,
 ct1: 34,
 ct2: 0,
 ct3: 7,
 ct4: 572,
 ct5: 527 } }

这是我的代码:

mappings.forEach(function(room) {
  var hash = {};
  hash.floor = room.floor;
  hash.name = room.name;
  hash.room_type = room.room_type;
  hash.energy_ac = 0;
  room.energy_ac.forEach(function(device) {
    device.channels.forEach(function(channel){
      hash.energy_ac += room[device][channel];
    });
  });

room[device][channel]对我不起作用。我也试过room[divice][channel。我不知道如何获得channel的值。如有任何帮助,我们将不胜感激。

设备嵌套在energy_ac中,因此您无法直接从房间访问它。你需要做一些类似room.energy_ac[device].channels[channel]的事情。但这仍然不起作用,因为通道不是数组的索引,而是当前项,即通道值。您真正需要做的只是运行hash.energy_ac += channel,因为通道是您无论如何都要添加的数字。

我认为这里的主要问题是,当能量实际存储在data对象中时,您正试图从device对象获取能量。需要索引到data对象中的存储在device中。

假设你想要每个房间的总能量_ac,你需要做的是:

for each room:
    set hash.energy_ac = 0
    for each device in room's energy_ac:
        for each channel in this device:
          add the energy of this device and channel to hash.energy_ac

因此,对于mappings(1301)中的一个房间,energy_ac应该是75。其energy_ac包括设备15062:信道ct1(34),加上设备15063:信道ct2(0)+ct3(7)。34+34+7=75。

这里有一个JSFiddle,其中包含(我认为是)您想要的实现。

此外,由于_id值不是字符串,我收到了控制台错误。