moss
moss

Reputation: 25

How to extract certain elements from an array?

The below code accesses and array with objects in it. Each object has and id, an url and a Tag. I want to be able to basically use the Tag to display a random URL connected with a tag I suggest.

For example i want window.currentlyShownOffer.Tag to always be equal to Garden. Garden is a Tag.

function receivedData(data) {

        function changeOfferPicture() {
            if (window.currentlyShownOffer) {
                var tagArray = data[window.currentlyShownOffer.Tag];
                tagArray.splice(tagArray.indexOf(currentlyShownOffer), 1);
                //alert(window.currentlyShownOffer.ImagesId);

            }


            var tags = Object.keys(data);
            var randomTag = tags[Math.floor(Math.random() * tags.length)];
            var tagArray = data[randomTag];


            window.currentlyShownOffer = tagArray[Math.floor(Math.random() * tagArray.length)];
            document.getElementById('content').src = window.currentlyShownOffer.ImagesPath;
        };
}

Any idea of what the array looks like:

{“Garden”:[{“ImagesId”:”63”,”ImagesPath”:”http….”,”Tag”:”Garden”},{“Garden”:[{“ImagesId”:”64”,”ImagesPath”:”http….”,”Tag”:”Garden”}]{“Food”:[{“ImagesId”:”63”,”ImagesPath”:”http….”,”Tag”:”Food”},{“Food”:[{“ImagesId”:”63”,”ImagesPath”:”http….”,”Tag”:”Food”}]

UPDATE

function receivedData(data) {

        function changeOfferPicture() {
            if (window.currentlyShownOffer) {
                var tagArray = data[window.currentlyShownOffer.Tag];
                tagArray.splice(tagArray.indexOf(currentlyShownOffer), 1);
                //alert(window.currentlyShownOffer.ImagesId);

            }


            var tags = Object.keys(data);
            var randomTag = tags[Math.floor(Math.random() * tags.length)];
            var tagArray = data[randomTag];

         function getObjectsWithTag(tag, tagArray){
                return tagArray.filter(function(item){
                return item.tag === tag;
            });
            }

            getObjectsWithTag(Garden);


            window.currentlyShownOffer = tagArray[Math.floor(Math.random() * tagArray.length)];
            document.getElementById('content').src = window.currentlyShownOffer.ImagesPath;
        };
}

Here's maybe a better idea of the array:

{
“Garden’ : [{‘ImagesId”: ”38”, ”ImagesPath”: ”url”, ”Tag”: ”Food”}],
“Sport’: [{‘ImagesId”: ”64”, ”ImagesPath”: ”url”, ”Tag”: ”Sport”}]
}

Upvotes: 0

Views: 89

Answers (1)

ampersand
ampersand

Reputation: 4314

You can use Array.filter() to get all items with a specific tag. If tagArray has Objects with a key tag containing the tag name:

function getObjectsWithTag(tag, tagArray){
  return tagArray.filter(function(item){
    return item.tag === tag;
  });
}

The returned value will be an array containing only items that matched the tag name in the original tagArray.

Upvotes: 1

Related Questions