JavaScript oleh Radu TM • June 23, 2022
const obj = {
foo: '🍎',
bar: '🍌',
baz: null,
qux: undefined,
};
// iterasi atas properti enumerable objek itu sendiri
for (const key of Object.keys(obj)) {
// jika nilai properti adalah null, hapus properti tersebut
if (obj[key] === null) {
delete obj[key];
}
}
console.log(obj);
// { foo: '🍎', bar: '🍌' }
0
29.988
JavaScript oleh Radu TM • June 23, 2022
const obj = {
name: 'John',
age: null,
job: 'teacher',
city: null
};
// gunakan untuk loop
for (let key in obj) {
if (obj[key] === null) {
delete obj[key];
}
}
// gunakan Object.keys()
const obj = {
name: 'John',
age: null,
job: 'teacher',
city: null
};
const newObj = Object.keys(obj).reduce((acc, key) => {
if (obj[key]) {
acc[key] = obj[key];
}
return acc;
}, {});
console.log(newObj); // { name: 'John', job: 'teacher' }
0
29.988