[英]Javascript iterate over array of hash and get keys
我已经使用带有MySQL数据库的NodeJ构建了自己的应用程序。 当我获取一个表时,我会得到一些看起来像这样的值。 我的实际要求是我需要从该数组获取哈希键。
[ 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
变量,然后当我尝试遍历var sysConValues
for (var i = 0; i < rows.length; i++) {
for (var key in sysConValues[i]) {
console.log(sysConValues);
}
}
我将输出输出为0而不是['FieldName', 'Input']
。 我在这里做错了什么以及如何从sysConValues
获取密钥。
您不需要使用JSON.stringify()
和JSON.parse()
删除RowDataPacket
。 您可以按原样保留它并遍历原始数组。
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);
}
});
我对您的问题的理解是,您需要数组中每个对象的键。
因此,您可以使用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);
您问题的答案
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.