使用变量访问嵌套Javascript对象
我试图找到每个通道的总和,得到能量的总能量。这是映射使用变量访问嵌套Javascript对象,javascript,Javascript,我试图找到每个通道的总和,得到能量的总能量。这是映射 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,
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];
});
});
房间[设备][频道]对我不起作用。我还尝试了房间[设备].频道。我不知道如何获得频道的价值。任何帮助都将不胜感激。设备嵌套在energy_ac内部,所以您不能直接从房间访问它。您需要执行类似于
room.energy\u ac[device].channels[channel]
的操作。但这仍然行不通,因为通道不是数组的索引,而是当前项,即通道值。你真正需要做的就是运行hash.energy\u ac+=channel
,因为channel是你无论如何都要添加的数字。我认为这里的主要问题是你试图从设备
对象获取能量,而它实际上存储在数据
对象中。需要索引到数据
对象中的键存储在设备
中
假设您想要每个房间的总能量,您需要做的是:
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
因此,对于映射
(1301)中的一个房间,能量_ac
应为75。其energy\u ac
由设备15062:channel ct1(34)和设备15063:channels ct1(34)+ct2(0)+ct3(7)组成。34+34+7=75
下面是一个关于(我认为是)您想要的实现的示例
另外,由于
\u id
值不是字符串,我收到了控制台错误。你能发布一个可复制的示例吗?我发布了我的实际代码,这是你的意思吗?