JS Object Iterations
In this page:
for (const key in object) {
// object[key]
}
Object.keys(object);
Object.values(object);
Object.entries(object);
Object.keys() से Property नाम पाना
Object.keys(obj) एक असली array लौटाता है जिसमें केवल object की अपनी enumerable property के नाम strings के रूप में होते हैं -- तब उपयोगी जब आपको जानना हो कि object में कौन सी properties हैं, या नामों की उस सूची पर array methods (map, filter) इस्तेमाल करने हों।
उदाहरण: Getting Property Names with Object.keys()
const user = { name: "Sam", age: 30 };
console.log(Object.keys(user));
Object.values() से Values पाना
Object.values(obj) केवल संबंधित values को असली array के रूप में लौटाता है, उसी क्रम में जिसमें Object.keys() उनके नाम लौटाता -- तब उपयोगी जब property के नाम खुद मायने नहीं रखते, केवल उनमें जो store है वह मायने रखता है।
उदाहरण: Getting Values with Object.values()
const user = { name: "Sam", age: 30 };
console.log(Object.values(user));
Object.entries() से Key-Value जोड़ियाँ पाना
Object.entries(obj) [key, value] जोड़ियों का array लौटाता है -- हर एक दो-item का छोटा array -- जो Object.keys() और Object.values() के फ़ायदों को एक call में मिलाता है, और for...of loop या map() call के भीतर destructuring के साथ खास तौर पर अच्छा काम करता है।
उदाहरण: Getting Key-Value Pairs with Object.entries()
const user = { name: "Sam", age: 30 };
console.log(Object.entries(user));
for...in से Loop करना
for...in बिना बीच के array के सीधे object की enumerable property नामों पर loop करता है, भावना में array पर for...of जैसा -- Object.keys()/entries() से थोड़ा पुराना पैटर्न, लेकिन फिर भी आमतौर पर दिखता है और कभी-कभी साधारण loop के लिए ज़्यादा सुविधाजनक होता है।
उदाहरण: Looping with for...in
// Declare the constant `user`, set to `{ name: "Sam", age: 30 }`
// Declare the constant `user`, set to `{ name: "Sam", age: 30 }`
const user = { name: "Sam", age: 30 };
// Loop over the enumerable keys of `user`, binding each to `key`
// Loop over the enumerable keys of `user`, binding each to `key`
for (let key in user) {
// Print `key, user[key]` to the console
// Print `key, user[key]` to the console
console.log(key, user[key]);
}
सही Iteration Method चुनना
आधुनिक code में आमतौर पर Object.keys()/values()/entries() को तरजीह दी जाती है, क्योंकि वे असली arrays लौटाते हैं जो array methods के साथ स्वाभाविक रूप से काम करते हैं -- for...in वैध बना रहता है, खासकर सीधे सरल loop के लिए, पर array लौटाने वाले methods नतीजों को filter, map या sort करने के लिए ज़्यादा लचीलापन देते हैं।
उदाहरण: Choosing the Right Iteration Method
const user = { name: "Sam", age: 30 };
console.log(Object.entries(user).map(([key, value]) => `${key}: ${value}`));
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: