How to iterate over object properties in TypeScript

3 Answers

0 votes
// Defining an interface to specify the structure of the object.
interface User {
    id: number;
    name: string;
    age: number;
    city: string;
}
 
  
let user: User = {
    id: 94820083,
    name: "Emma",
    age: 37,
    city: "Bristol"
};
  
Object.entries(user).map(data => {
    console.log(data);
    console.log(data[0], ",", data[1]);
});
 
  
     
/*
run:
 
["id", 94820083] 
"id",  ",",  94820083 
["name", "Emma"] 
"name",  ",",  "Emma" 
["age", 37] 
"age",  ",",  37 
["city", "Bristol"] 
"city",  ",",  "Bristol" 
 
*/

 



answered Mar 2, 2025 by avibootz
0 votes
// Defining an interface to specify the structure of the object.
interface User {
    id: number;
    name: string;
    age: number;
    city: string;
}
 
  
let user: User = {
    id: 94820083,
    name: "Emma",
    age: 37,
    city: "Bristol"
};
  
Object.entries(user).forEach(data => {
    console.log(data);
    console.log(data[0], ",", data[1]);
});
 
  
     
/*
run:
 
["id", 94820083] 
"id",  ",",  94820083 
["name", "Emma"] 
"name",  ",",  "Emma" 
["age", 37] 
"age",  ",",  37 
["city", "Bristol"] 
"city",  ",",  "Bristol" 
 
*/

 



answered Mar 2, 2025 by avibootz
0 votes
// Defining an interface to specify the structure of the object.
interface User {
    id: number;
    name: string;
    age: number;
    city: string;
}
 
  
let user: User = {
    id: 94820083,
    name: "Emma",
    age: 37,
    city: "Bristol"
};
  
for (const data of Object.entries(user)) {
    console.log(data);
    console.log(data[0], ",", data[1]);
}
 
  
     
/*
run:
 
["id", 94820083] 
"id",  ",",  94820083 
["name", "Emma"] 
"name",  ",",  "Emma" 
["age", 37] 
"age",  ",",  37 
["city", "Bristol"] 
"city",  ",",  "Bristol" 
 
*/

 



answered Mar 2, 2025 by avibootz
...