You can easily achieve the result using Object.keys and reduce
Loop over the keys
of object obj
using Object.keys
and set the properties of new object only if it is not empty
You can check for the type of value using typeof
operator
1) string
: typeof
will return string
and check for the length
property
2) array
: You can use Array.isArray
and it will return boolean
value whether the object is an array or not
3) object
: You can first get all keys using Object.keys
and then check if there is any property exist on that object or not using length
property
Since, arrays
are object
in JS, so you can directly use
(typeof value === "object" && Object.keys(value).length)
to check where it is an object and if it contain any property or not
You can create a filter as
if (value !== "" && Object.keys(value).length) acc[key] = value;
const obj = {
key1: "asdf",
key2: {},
key3: ["a", "b", "c"],
key4: [],
key5: "",
};
const result = Object.keys(obj).reduce((acc, key) => {
const value = obj[key];
if (value !== "" && Object.keys(value).length) acc[key] = value;
return acc;
}, {});
console.log(result);