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

Time:01-20

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?

CodePudding user response:

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

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