Home > Enterprise >  Ramda: Remove empty object having dynamic keys
Ramda: Remove empty object having dynamic keys

Time:12-27

I have this object where addon_sizes keys are dynamic i.e "1","2", "3", "4":

const sizes = {
 "addon_sizes": {
        "1": ["a", "b"],
        "2": ["c"],
        "3": null,
        "4": []
    }
}

I need to remove all key/value pairs in this object where the value is null/undefined/empty array.

So the keys "3" and "4" should be removed from the list.

So far what i have tried is:

const newObj = R.reject(R.anyPass([R.isEmpty, R.isNil]))(sizes.addon_sizes);

But this doesn't remove the null or empty values.

CodePudding user response:

Since you've tagged javascript:

You can iterate through the object entries and use the delete keyword to delete the negative or negative length properties.

const sizes = {
    "addon_sizes": {
        "1": ["a", "b"],
        "2": ["c"],
        "3": null,
        "4": []
    }
};

Object.entries(sizes.addon_sizes).forEach(([ key, value ]) => {
  if(!value || !value.length)
    delete sizes.addon_sizes[key];
});

console.log(sizes);

CodePudding user response:

Create a new object by picking all properties that are not empty or nil:

const { pickBy, complement, anyPass, isEmpty, isNil } = R

const fn = pickBy(complement(anyPass([isEmpty, isNil])))

const sizes = {"addon_sizes":{"1":["a","b"],"2":["c"],"3":null,"4":[]}}

const result = fn(sizes.addon_sizes)

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  • Related