Javascript迭代哈希数组并获取密钥

时间:2018-03-30 05:24:14

标签: javascript node.js express

我使用带有MySQL数据库的NodeJs构建了我自己的应用程序。当我获取一个表时,我得到了一些看似这样的值。我的实际要求是我需要从这个数组中获取哈希键。

 [ RowDataPacket { FieldName: 'aoc_com', Input: 'ipc3' },
  RowDataPacket { FieldName: 'build', Input: 'RH' },
  RowDataPacket { FieldName: 'daq_type', Input: 'Full' },
  RowDataPacket { FieldName: 'endingport', Input: '8030' },
  RowDataPacket { FieldName: 'id_type', Input: 'TAM9' },
  RowDataPacket { FieldName: 'od_build_type', Input: 'Test_OD' },

首先,我尝试使用JSON.stringify(rows)删除RowDataPacket。现在我的数组看起来像这样

[{"FieldName":"aoc_com","Input":"ipc3"},{"FieldName":"build","Input":"RH"},{"FieldName":"daq_type","Input":"Full"},{"FieldName":"endingport","Input":"8030"},{"FieldName":"id_type","Input":"TAM9"},{"FieldName":"od_build_type","Input":"Test_OD"}]

然后我将此输出存储在变量sysConValues中,然后当我尝试迭代变量sysConValues

for (var i = 0; i < rows.length; i++) { 
  for (var key in sysConValues[i]) { 
     console.log(sysConValues); 
  }
}

我输出为0而不是['FieldName', 'Input']。我在这里做错了什么以及如何从sysConValues获取密钥。

3 个答案:

答案 0 :(得分:2)

您不需要使用RowDataPacketJSON.stringify()删除JSON.parse()。您可以保留原样并迭代原始数组。

var packets = [ RowDataPacket { FieldName: 'aoc_com', Input: 'ipc3' },
    RowDataPacket { FieldName: 'build', Input: 'RH' },
    RowDataPacket { FieldName: 'daq_type', Input: 'Full' },
    RowDataPacket { FieldName: 'endingport', Input: '8030' },
    RowDataPacket { FieldName: 'id_type', Input: 'TAM9' },
    RowDataPacket { FieldName: 'od_build_type', Input: 'Test_OD' }];

packets.forEach(function (packet) {
    for(var key in packet) {
        if(!packet.hasOwnProperty(key)) { continue; }

        console.log(key);
    }
});

答案 1 :(得分:1)

我通过你的问题理解的是你想要数组中每个对象的键。

因此,您可以使用Array.prototype.map获取密钥。

let arr = [{
    FieldName: 'aoc_com',
    Input: 'ipc3'
  },
  {
    FieldName: 'build',
    Input: 'RH'
  },
  {
    FieldName: 'daq_type',
    Input: 'Full'
  },
  {
    FieldName: 'endingport',
    Input: '8030'
  },
  {
    FieldName: 'id_type',
    Input: 'TAM9'
  },
  {
    FieldName: 'od_build_type',
    Input: 'Test_OD'
  }
];

let keyArr = arr.map(o => Object.keys(o));
console.log(keyArr);

答案 2 :(得分:0)

您的问题的答案

var array = [{"FieldName":"aoc_com","Input":"ipc3"}, 
  {"FieldName":"build","Input":"RH"}, 
  {"FieldName":"daq_type","Input":"Full"}, 
  {"FieldName":"endingport","Input":"8030"}, 
  {"FieldName":"id_type","Input":"TAM9"}, 
  {"FieldName":"od_build_type","Input":"Test_OD"}];
var hashResult = {};
for (var key in array) { 
  console.log(array[key].FieldName); 
  hashResult[`${array[key].FieldName}`] = array[key].Input;
}

console.log(hashResult);
相关问题