1

I am trying to retrieve posts from the JSON data with a certain tag.

data: any = 
[
    {"id": 1, 
    "title": "title 1", 
    "description": "Lorem Ipsum.", 
    "by": "author",
    "tags": [
        { "tag":"facebook" }, 
        { "tag": "twitter" } ]
    },
    {"id": 2,
    "title": "title 2",
    "description": "Lorem Ipsum.",
    "by": "author",
    "tags": [
        { "tag": "google" }, 
        { "tag": "twitter" } ]
    },
    {"id": 3,
    "title": "title 3",
    "description": "Lorem Ipsum.",
    "by": "author",
    "tags": [ 
        { "tag": "reddit" }, 
        { "tag": "instagram" } ]
    },
    {"id": 4,
    "title": "title 4",
    "description": "Lorem Ipsum.",
    "by": "author",
    "tags": [
        { "tag":"reddit" },
        { "tag":"9gag" } ]
    }
];

The output I want to retrieve are the post using a certain tag. let's say that the certain tag I want is "9gag", the result should output something like this:

result: any = 
    [
        {"id": 3,
        "title": "title 3",
        "description": "Lorem Ipsum.",
        "by": "author",
        "tags": [ 
            { "tag": "reddit" }, 
            { "tag": "instagram" } ]
        },
        {"id": 4,
        "title": "title 4",
        "description": "Lorem Ipsum.",
        "by": "author",
        "tags": [
            { "tag":"reddit" },
            { "tag":"9gag" } ]
        }
    ];

2 Answers2

0

You have a list of Articles, so you can use the filter:

let result = data.filter(...)

and then apply the condition:

article.tags.some(tag => (tag.tag.includes(yourString)))

so finally:

let yourString = "9gag";
data.filter(
  article => (article.tags.some(
                tag => (tag.tag.includes(yourString))
             )
  )
);

A great example here: https://stackoverflow.com/a/44313087/7604006

NikNik
  • 2,191
  • 2
  • 15
  • 34
0

You can use Array.filter() and Array.some() to do that.

const data = [{ "id": 1, "title": "title 1", "description": "Lorem Ipsum.", "by": "author", "tags": [{ "tag": "facebook" }, { "tag": "twitter" } ] }, { "id": 2, "title": "title 2", "description": "Lorem Ipsum.", "by": "author", "tags": [{ "tag": "google" }, { "tag": "twitter" } ] }, { "id": 3, "title": "title 3", "description": "Lorem Ipsum.", "by": "author", "tags": [{ "tag": "reddit" }, { "tag": "instagram" } ] }, { "id": 4, "title": "title 4", "description": "Lorem Ipsum.", "by": "author", "tags": [{ "tag": "reddit" }, { "tag": "9gag" } ] } ]; 

function getPostsByTag(posts, tag) {
  return posts.filter(post => post.tags.some(item => item.tag === tag));
}

console.log(getPostsByTag(data, "9gag"));
Nikhil
  • 6,493
  • 10
  • 31
  • 68