A
A
alpha-kappa2017-08-01 17:52:58
JavaScript
alpha-kappa, 2017-08-01 17:52:58

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": {}
  }

You need to filter it by removing "cars" with empty property values ​​or no properties, in the example above these are "car3" and "car4".
If it were an array , you could use Array.prototype.filter() :
cars.filter((car) => {
  // делаем проверку на наличие и заполненность свойств
  return "результат проверки";
})

But I have this object , and objects do not have a filter method.
At the moment, I came up with a solution through key arrays: I get an array of object keys, filter it, and then remove keys from the object that are not in the filtered key array.
let carsKeys = Object.keys(cars);
let carsKeysFilterd = carsKeys.filter((key) => {
  // проверяем пункт cars[key] на соответствие требованиям
  return "результат проверки";
})
carsKeys.forEach((key) => {
  if (carsKeysFiltered.indexOf(key) === -1) delete cars[key];
})

I understand that this, to put it mildly, is not the most concise solution, so I came to you for help.
How best to organize the management of this object in accordance with the specified requirements?
Clarification I need to do this on the server side. Perhaps you know a suitable npm module for this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
Larisa Moroz, 2017-08-01
@larisamoroz

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);

where filterFunc is your validation function, which is passed only the value of a specific key

G
gleendo, 2017-08-01
@evgeniy8705

// Первое что пришло на ум. Вероятнее всего есть более оптимальное решение

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;

Y
Yumeiro, 2017-08-01
@Yumeiro

Object.entries(cars).map(a=>Object.entries(a[1]).filter(b=>b[1].length).length?a:delete cars[a[0]]);

Not very pretty, but a one-liner.
If there are no properties in the nested object or they are empty, then the property is removed. I can add to delete those properties whose values ​​contain at least one empty property, the code will not increase this much

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question