I have list object like below
0:""
1:""
3:"tag1"
4:"tag2
This is my question how to ignore empty value.I need a result like the below.
0:"tag1"
1:"tag2
Thanks for help me.
I have list object like below
0:""
1:""
3:"tag1"
4:"tag2
This is my question how to ignore empty value.I need a result like the below.
0:"tag1"
1:"tag2
Thanks for help me.
One naive solution could be:
const obj = {
0: "",
1: "",
2: "tag1",
3: "tag2"
};
const newObj = Object.fromEntries(
Object.entries(obj).filter(([k, v]) => v)
);
Object.entries
turns an object into an array of keys and values.
For example
Object.entries(obj)
becomes
[
[
"0",
""
],
[
"1",
""
],
[
"2",
"tag1"
],
[
"3",
"tag2"
]
]
which is then filtered by whether the value is "truthy"
.filter(([k,v]) => v))
and finally turned back into an object
Object.fromEntries
If that is an array, you can use filter
.
let o = ["","",,"tag1","tag2"];
let res = o.filter(Boolean); // or o.filter(x => x);
console.log(res);
To be more precise, you could use:
let res = o.filter(x => x !== '');