Home > Enterprise >  I'd like to filter out objects which do not have an ext key on them
I'd like to filter out objects which do not have an ext key on them

Time:09-29

How can I remove objects which do not have an ext key? I want to take pictures, but there is a problem because some objects do not have a picture. I'm confused about filtering. Can it be done with reduce or filter?

{
  "posts": [
    {
      "filename": "1647706792183",
      "ext": ".png",
      "w": 300,
      "h": 450,
      "tn_w": 166,
      "tn_h": 250,
      "tim": 1664328637690788,
      "time": 1664328637,
      "md5": "Omk9VtmPOD1U38U1OOAP/w==",
      "fsize": 200271,
      "resto": 0,
      "country": "DK",
      "bumplimit": 0,
      "imagelimit": 0,
      "semantic_url": "f1-relentless-formula-one-general-all-smiles",
      "replies": 378,
      "images": 155,
      "unique_ips": 102,
      "tail_size": 50
    },
    {
      "now": "09/27/22(Tue)21:31:17",
      "name": "Anonymous",
      "resto": 123946553,
    }
  ]
}

CodePudding user response:

You can use .filter to run a function that returns true/false for each item of your data.

const data = { posts: [ .... ] };

const postsWithExt = data.posts.filter(post => post.ext !== undefined);

If you want to filter falsy values for .ext then use

posts.filter(post => !post.ext)

CodePudding user response:

You can just filter your posts array where the ext property exists.

e.g.

const data = {
  "posts": [{
      "filename": "1647706792183",
      "ext": ".png",
      "w": 300,
      "h": 450,
      "tn_w": 166,
      "tn_h": 250,
      "tim": 1664328637690788,
      "time": 1664328637,
      "md5": "Omk9VtmPOD1U38U1OOAP/w==",
      "fsize": 200271,
      "resto": 0,
      "country": "DK",
      "bumplimit": 0,
      "imagelimit": 0,
      "semantic_url": "f1-relentless-formula-one-general-all-smiles",
      "replies": 378,
      "images": 155,
      "unique_ips": 102,
      "tail_size": 50
    },
    {
      "now": "09/27/22(Tue)21:31:17",
      "name": "Anonymous",
      "resto": 123946553,
    }
  ]
};

const result = data.posts.filter(x => x.ext);

console.log(result);

  • Related