简体   繁体   中英

Navigating/Iterating in object as Interface to obtain key-value pair

export interface Worker {
  salary?: number;
  manager?: boolean;
  name?: string;
  hired?: Date;
}

const worker1: Worker = { salary: 5000, manager: true, name: "Bob", birth: new Date() };

I need to obtain all pairs of attributes as key - value.

for (const [key, value] of worker1????) {
    console.log("key: '" + key + "', value: " + value); // to do other needed operations
}

The output expected for this log Question is:

key: 'salary', value: 5000
key: 'manager', value: true
key: 'name', value: Bob
key: 'birth', value: xxxxx

How achieve that?

I think you just want the Object.entries() method ?

for (const [key, value] of Object.entries(worker1)) {
    console.log("key: '" + key + "', value: " + value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM