JavaScript di Victor Talmacinschi • June 23, 2022
const obj = {
name: '',
email: '[email protected]',
phone: '',
};
// possiamo usare Object.keys(obj) per ottenere un array di chiavi dell'oggetto
// quindi, possiamo usare il metodo .filter() per rimuovere le chiavi i cui valori sono stringhe vuote
const newObj = Object.keys(obj)
.filter(key => obj[key] !== '')
.reduce((acc, key) => {
// Infine, possiamo usare .reduce() per trasformare il nostro array di chiavi in un oggetto
acc[key] = obj[key];
return acc;
}, {});
console.log(newObj);
// { email: '[email protected]' }
0
32.425
JavaScript di Victor Talmacinschi • June 23, 2022
const obj = {
name: '',
age: 0,
address: '',
};
// utilizzando il ciclo for..in
for (const key in obj) {
// controlla se la proprietà è una stringa vuota
if (obj[key] === '') {
// eliminare la proprietà
delete obj[key];
}
}
// Uscita: { age: 0 }
console.log(obj);
0
32.425
JavaScript di Victor Talmacinschi • June 23, 2022
const obj = {
foo: '🍎',
bar: '🍌',
baz: null,
qux: undefined,
};
// iterare sulle proprietà enumerabili dell'oggetto
for (const key of Object.keys(obj)) {
// se il valore della proprietà è null, eliminarla
if (obj[key] === null) {
delete obj[key];
}
}
console.log(obj);
// { foo: '🍎', bar: '🍌' }
0
11.315
JavaScript di Victor Talmacinschi • June 23, 2022
const obj = {
name: 'John',
age: null,
job: 'teacher',
city: null
};
// utilizzare il ciclo for
for (let key in obj) {
if (obj[key] === null) {
delete obj[key];
}
}
// utilizzare 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
11.315