@catherine_wintheiser
Существует несколько способов проверить объект на пустоту:
- С помощью метода Object.keys():
1
2
3
4
5
6
|
const obj = {};
if (Object.keys(obj).length === 0) {
console.log('Object is empty');
} else {
console.log('Object is not empty');
}
|
- С помощью цикла for...in:
1
2
3
4
5
6
7
8
9
10
11
|
const obj = {};
let isEmpty = true;
for (let key in obj) {
isEmpty = false;
break;
}
if (isEmpty) {
console.log('Object is empty');
} else {
console.log('Object is not empty');
}
|
- С помощью метода Object.getOwnPropertyNames():
1
2
3
4
5
6
|
const obj = {};
if (Object.getOwnPropertyNames(obj).length === 0) {
console.log('Object is empty');
} else {
console.log('Object is not empty');
}
|
- С помощью метода JSON.stringify():
1
2
3
4
5
6
|
const obj = {};
if (JSON.stringify(obj) === '{}') {
console.log('Object is empty');
} else {
console.log('Object is not empty');
}
|