我使用MySQL数据库构建了自己的应用程序。当我获取桌子时,我会得到一些看起来像这样的价值。我的实际要求是我需要从此数组中获取哈希的钥匙。
[ 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(行(删除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);