-3

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Saeed As
  • 9
  • 3

2 Answers2

1

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
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
1

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 !== '');
Unmitigated
  • 76,500
  • 11
  • 62
  • 80