Dalam ES6 / 2015 Anda dapat mengulangi objek seperti ini: (menggunakan fungsi panah )
Object.keys(myObj).forEach(key => {
console.log(key); // the name of the current key.
console.log(myObj[key]); // the value of the current key.
});
jsbin
Di ES7 / 2016 Anda bisa menggunakan dan Object.entries
bukan Object.keys
melalui objek seperti ini:
Object.entries(myObj).forEach(([key, val]) => {
console.log(key); // the name of the current key.
console.log(val); // the value of the current key.
});
Di atas juga akan berfungsi sebagai satu-liner :
Object.entries(myObj).forEach(([key, val]) => console.log(key, val));
jsbin
Jika Anda ingin mengulangi objek bersarang juga, Anda dapat menggunakan fungsi rekursif (ES6):
const loopNestedObj = obj => {
Object.keys(obj).forEach(key => {
if (obj[key] && typeof obj[key] === "object") loopNestedObj(obj[key]); // recurse.
else console.log(key, obj[key]); // or do something with key and val.
});
};
jsbin
Sama seperti fungsi di atas, tetapi dengan ES7 Object.entries()
bukannya Object.keys()
:
const loopNestedObj = obj => {
Object.entries(obj).forEach(([key, val]) => {
if (val && typeof val === "object") loopNestedObj(val); // recurse.
else console.log(key, val); // or do something with key and val.
});
};
Di sini kita loop melalui objek bersarang mengubah nilai dan mengembalikan objek baru dalam sekali pakai menggunakan Object.entries()
dikombinasikan dengan Object.fromEntries()
( ES10 / 2019 ):
const loopNestedObj = obj =>
Object.fromEntries(
Object.entries(obj).map(([key, val]) => {
if (val && typeof val === "object") [key, loopNestedObj(val)]; // recurse
else [key, updateMyVal(val)]; // or do something with key and val.
})
);