我有嵌套的对象,其中包含数据库服务器的详细信息。从嵌套对象中,我必须搜索名为“数据库”的键名,并显示其值。
我通过这样的调用找到了解决方案:
var database = (Object.entries((Object.entries(connection))[3]))[1][1].database;
但是一些时间位置正在改变。因此无法获得价值。因此,如何在嵌套对象中找到键以找到值。请帮助。预先感谢。
console.log("connection:", Object.entries(connection) );
结果
connection: [ [ '_events',
[Object: null prototype] { end: [Function: _removeFromPool], error: [Function] } ],
[ '_eventsCount', 2 ],
[ 'config',
ConnectionConfig {
host: 'localhost',
port: 336,
localAddress: undefined,
socketPath: undefined,
user: 'user',
password: 'password',
database: 'dbname',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: [Pool],
ssl: false,
multipleStatements: true,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 521167,
protocol41: true } ],
[ '_socket',
Socket {
connecting: false,
_hadError: false,
_handle: [TCP],
_parent: null,
_host: null,
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
_writableState: [WritableState],
writable: true,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
timeout: 0,
[Symbol(asyncId)]: 26,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]:
Timeout {
_called: false,
_idleTimeout: -1,
_idlePrev: null,
_idleNext: null,
_idleStart: 8926,
_onTimeout: null,
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(unrefed)]: true,
[Symbol(asyncId)]: 29,
[Symbol(triggerId)]: 25 },
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0 } ],
[ '_protocol',
Protocol {
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
readable: true,
writable: true,
_config: [ConnectionConfig],
_connection: [PoolConnection],
_callback: null,
_fatalError: null,
_quitSequence: null,
_handshake: true,
_handshaked: true,
_ended: false,
_destroyed: false,
_queue: [Array],
_handshakeInitializationPacket: [HandshakeInitializationPacket],
_parser: [Parser] } ],
[ '_connectCalled', true ],
[ 'state', 'authenticated' ],
[ 'threadId', 2859 ],
[ '_pool',
Pool {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
config: [PoolConfig],
_acquiringConnections: [],
_allConnections: [Array],
_freeConnections: [],
_connectionQueue: [],
_closed: false } ] ];
以及现在正在做什么,
var database = (Object.entries((Object.entries(connection))[3]))[1][1].database;
console.log(database);
output: dbname
答案 0 :(得分:1)
要回答您的直接问题:
var db = ''
Object.entries(connection).foreach(item => {
if (item[0] === 'config') db = item[1].database
})
但是,您应该能够直接访问该值,而无需在数组中旋转连接对象:
connection.config.database
答案 1 :(得分:0)
let config = connection.filter(([key, value]) => key === "config")[0][1]
let database = config.database // dbname