Работа с объектами
Подскажите как переделать код так чтобы console.log('object is full of properties') выводилась только тогда, когда в объекте два и более свойства?
const testObject = {
name: 'Dmitriy',
age: 99,
location: 'Monaco'
};
function isEmpty (object) {
for (let key in object) {
if (object.hasOwnProperty(key)) {
return console.log('object is full of properties');
}
}
return console.log('object is empty');
}
isEmpty(testObject);
Ответы (2 шт):
Автор решения: Sergiks
→ Ссылка
Object.keys(obj) возвращает массив собственных итерируемых строковых свойств. Как раз то, что хочется пересчитать в задаче. Из названия функции "isEmpty" следует, что она возвращает Булево значение (true / false).
const isEmpty = obj => Object.keys(obj).length <= 2;
Использование:
console.log( isEmpty({ a: "AAA" }) ? 'object is empty' : 'object is full of properties' );
// выведет "object is empty"
console.log( isEmpty({ a: "AAA", b: "BB", c: "C" }) ? 'object is empty' : 'object is full of properties' );
// выведет "object is full of properties"
Автор решения: Andrei
→ Ссылка
Вот так это можно сделать:
const testObject = {
name: 'Dmitriy',
age: 99,
location: 'Monaco'
};
const testObject1 = {
name: 'Dmitriy'
};
const testObject2 = {};
function isEmpty(object) {
let count = 0;
for (let key in object) {
if (object.hasOwnProperty(key)) {
++count;
}
if (count > 1)
return console.log('object is full of properties');
}
return console.log('object is empty');
}
isEmpty(testObject);
isEmpty(testObject1);
isEmpty(testObject2);