Answer the question
In order to leave comments, you need to log in
How to remove empty properties or properties with values cast to empty from an object?
There is an object:
let cars = {
"car1": {
"doors": [red,green],
"wheels": [blue,yellow]
},
"car2": {
"wheels": [black]
},
"car3": {
"doors": [],
"wheels": []
},
"car4": {}
}
cars.filter((car) => {
// делаем проверку на наличие и заполненность свойств
return "результат проверки";
})
let carsKeys = Object.keys(cars);
let carsKeysFilterd = carsKeys.filter((key) => {
// проверяем пункт cars[key] на соответствие требованиям
return "результат проверки";
})
carsKeys.forEach((key) => {
if (carsKeysFiltered.indexOf(key) === -1) delete cars[key];
})
Answer the question
In order to leave comments, you need to log in
Object.filter = function( obj, filtercheck) {
let result = {};
Object.keys(obj).forEach((key) => { if (filtercheck(obj[key])) result[key] = obj[key]; })
return result;
};
let carsFiltered = Object.filter(cars, filterFunc);
// Первое что пришло на ум. Вероятнее всего есть более оптимальное решение
let storage = {};
for (let car in cars) {
for (let prop in cars[car]) {
if (cars[car][prop].length != 0) {
storage[car] = cars[car];
}
}
}
cars = storage;
Object.entries(cars).map(a=>Object.entries(a[1]).filter(b=>b[1].length).length?a:delete cars[a[0]]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question